본문 바로가기
데이터베이스/JDBC

[JDBC] 트랜잭션 템플릿

by 거북이의 기술블로그 2024. 11. 6.

트랜잭션 매니저 코드

  • 트랜잭션 commit(), rollback() 반복 사용의 불편함
//트랜잭션 시작
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
     //비즈니스 로직
         bizLogic(fromId, toId, money);
         transactionManager.commit(status); //성공시 커밋 
     } catch (Exception e) {
         transactionManager.rollback(status); //실패시 롤백
         throw new IllegalStateException(e);
     }

 

트랜잭션 템플릿

  • 반복하는 부분 제거 (commit() , rollback())
  • 람다를 이용하여 표현
 public class TransactionTemplate {
     private PlatformTransactionManager transactionManager;
     public <T> T execute(TransactionCallback<T> action){..}
     void executeWithoutResult(Consumer<TransactionStatus> action){..}
 }
  • 메서드
    • execute() : 응답 값이 있을 때 사용
    • executeWithoutResult() : 응답 값이 없을 때 사용
public class TemplateTransactionEx {
     private final TransactionTemplate txTemplate;
     private final MemberRepositoryV3 memberRepository;
     
     
     public TemplateTransactionEx(PlatformTransactionManager transactionManager,MemberRepositoryV3 memberRepository) {
         this.txTemplate = new TransactionTemplate(transactionManager);
         this.memberRepository = memberRepository;
     }
     
     
     public void accountTransfer(String fromId, String toId, int money) throws SQLException {
         
         txTemplate.executeWithoutResult((status) -> {
             try {
                 //비즈니스 로직
                 bizLogic(fromId, toId, money);
             } catch (SQLException e) {
                 throw new IllegalStateException(e);
             }
         }); 
     }
     //...
}

 

'데이터베이스 > JDBC' 카테고리의 다른 글

[JDBC] 스프링 예외 변환기  (0) 2024.11.06
@Transactional  (0) 2024.11.06
[JDBC] 트랜잭션 매니저  (0) 2024.11.05
[JDBC] 트랜잭션  (0) 2024.11.05