ํธ๋์ญ์ ์ด๋ ?
DB์์ ์ํ๋ณํ์ ํ ์ฃผ๊ธฐ๋ฅผ ์๋ฏธํ๋ค.
์ฝ๊ฒ ๋งํด์ ๋ฐ๋ก ์ด์ ์ปค๋ฐ ์ดํ์ ์์ ๋ถํฐ, ์ด๋ฐ์ ๋ฐ ์์ ํ ์ต์ข ์ ์ผ๋ก ์ปค๋ฐ์ ๋ ๋ฆฌ๊ธฐ๊น์ง์ ์ฃผ๊ธฐ์ด๋ค.
@Transactional ์ด๋ ธํ ์ด์ ์, ํด๋น ์ด๋ ธํ ์ด์ ์ด ์ ์ฉ๋๋ ๋ฉ์๋๋ฅผ ํ๋์ ํธ๋์ญ์ ์ผ๋ก ๋ฌถ์ด์ฃผ๋ ์ญํ ์ ํ๋ค.
์์๋ก, "๊ตฌ๋งค์๊ฐ ํ๋งค์์๊ฒ ๊ธ์ก์ก๊ธ" ์ ๋๋ต์ ์ธ ์ฝ๋๋ก ๊ตฌํํด ๋ณด์๋ค.
1) ํธ๋์ญ์ ์์ฒด๋ฅผ ์ ์ฉํ์ง ์์ ๊ฒฝ์ฐ
2) @Transactional ๋์ try-catch๋ก ๊ตฌํํ ๊ฒฝ์ฐ
3) @Transactional์ ์ฌ์ฉํ ๊ฒฝ์ฐ
์๋ ์ธ๊ฐ์ง ๊ฒฝ์ฐ์ ์ฝ๋์ ๋ฌธ์ ์ ์ด ๊ฐ๊ฐ ๋ฌด์์ธ์ง ์ ๋ฆฌํด ๋ณด์๋ค.
1) ํธ๋์ญ์ ์์ฒด๋ฅผ ์ ์ฉํ์ง ์์ ๊ฒฝ์ฐ
@Autowired
private Buyer buyer
@Autowired
private Seller seller;
public void buy() {
buyer.send();
seller.receive();
}
์ด๋ฌํ ๊ฒฝ์ฐ ๋ฌธ์ ๊ฐ ์๊ธธ ์ ์๋ ๋ถ๋ถ์ด
receive() ๋ฉ์๋ ์์ฒด์ ๋ฌธ์ ๊ฐ ์์ด์ ํญ์ send() ๊น์ง๋ ๋งค๋ฒ ์คํ์ด ๋๊ณ receive() ๋ฉ์๋๋ ์คํ์ด ๋์ง ์์ ๊ฒฝ์ฐ
๊ตฌ๋งค์๋ ๋์ ๋ณด๋ด์ DB์์ ๊ธ์ก์ด ์ค์ด๋ค์๋๋ฐ, ํ๋งค์๋ ์ ๊ธ์ด ๋์ง ์์ DB์์ ๊ธ์ก ๋ณ๋์ด ์๋ ๊ฒฝ์ฐ์ด๋ค.
๋ฐ๋ผ์ ๋ฐ๋์ transaction์ ๊ฑธ์ด์, receive() ๊ฐ ์คํ๋์ง ๋ชปํ๊ณ ์๋ฌ๊ฐ ๋ ๊ฒฝ์ฐ ๋ฐ๋์ send() ๋ํ ๋กค๋ฐฑ๋์ด ์์๋ณต๊ตฌ ์์ผ์ฃผ์ด์ผ ํ๋ค.
2) @Transactional ๋์ try-catch๋ก ๊ตฌํํ ๊ฒฝ์ฐ
@Autowired
private PlatformTransactionManager transactionManager;
@Autowired
private Buyer buyer
@Autowired
private Seller seller;
public void buy() {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
try {
buyer.send();
seller.receive();
transactionManager.commit(status);
} catch(Exception e) {
transactionManager.rollback(status);
}
}
TransactionManager๋ก ์ง์ ์ปค๋ฐ๊ณผ ๋กค๋ฐฑ์ ์์ผ์ฃผ์๋ค.
๊ทธ๋ฌ๋ ์ฟผ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ ๋ฉ์๋์ ๋งค๋ฒ ์ค๋ณต๋๋ ์ฝ๋๋ฅผ ์์ฑํด ์ฃผ์ด์ผ ํ๋ ๋ถํธํจ์ด ์๋ค.
3) @Transactional์ ์ฌ์ฉํ ๊ฒฝ์ฐ
@Autowired
private Buyer buyer
@Autowired
private Seller seller;
@Transactional
public void buy() {
buyer.send();
seller.receive();
}
์ฌ์ฉ๋ ๋ฉ์๋ ์์ @Transactional ์ด๋ ธํ ์ด์ ๋ง ๋ถ์ฌ์ฃผ๋ฉด, ์์ try-catch๋ฌธ์ ์์ฑํ์ง ์์๋ ๋๋ค.
๋ง์ฝ ์๋์ ๊ฐ์ด ํด๋์ค์ ์ํ๋ ๋ชจ๋ ๋ฉ์๋์ @Transactional ์ด๋ ธํ ์ด์ ์ ์ ์ฉํ๊ณ ์ถ๋ค๋ฉด, ์ด๋ ธํ ์ด์ ์ ํด๋์ค ์์ ๋ถ์ฌ์ค๋ค.
ํด๋์ค ์์ @Transactional์ด ๋ถ์ด์์ผ๋ฉด, ํด๋์ค์ ์ํ ๋ชจ๋ ๋ฉ์๋์ ๊ฐ๊ฐ @Transactional์ด ๋ถ์ด์๋ค๊ณ ์๊ฐํ๋ฉด ๋๋ค.
@Transactional
public class AllQuery {
public void selectOne() { }
public int allCount() { }
public List<User> allUser() { }
/* ์๋์ ๋์ผํ๋ค
@Transactional
public void selectOne() { }
@Transactional
public int allCount() { }
@Transactional
public List<User> allUser() { }
*/
}
'Backend๐ฑ > Spring JPA' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Spring Data JPA 1. ์์๊ตฌ์กฐ์ ์ฃผ์ ์ธํฐํ์ด์ค (0) | 2023.04.19 |
---|---|
[JPA] Spring JPA CascadeType ์ข ๋ฅ (0) | 2023.04.09 |
[JPA] - @JoinColumn๊ณผ ์ฐ๊ด๊ด๊ณ์ ์ฃผ์ธ (mappedBy) (0) | 2023.04.09 |
[ Spring-Boot ] JPA @GeneratedValue ์ฌ์ฉํ๊ธฐ (0) | 2023.04.05 |
Spring JPA ์ฐ๊ด๊ด๊ณ ๋งคํ๐งธ (0) | 2023.04.05 |