Spring에서의 트랜잭션 처리 ⇒ Service 클래스에서 처리

 

 


 

JDBC 방식

public int insert(DeptDTO dto){
     Connection con = null;
try{
     con = DriverManager.getConnection(url, username, passwd);
..
     con.setAutoCommit(false);
     //DAO연동하면서 트랜잭션 처리

     con.commit();
}catch(Exception e){
     con.rollback();
   }
}
⇒ JDBC는 기본적으로 compile checked 예외를 발생시킨다. 무조건 try~catch, throws가 필수. (IOException, SQLException)

 

 

 


 

 

 

이전 MyBatis

public int insert(DeptDTO dto){       
SqlSession session = MySqlSessionFactory.openSession(); 
      
try{        
	 //DAO연동하면서 트랜잭션 처리 	
	 session.commit();     
}catch(Exception e){        
	 session.rollback();     
}finally{        
	 session.close();    
   }   
}
⇒ MyBatis는 기본적으로 compile unchecked 예외를 발생시킨다. (RuntimeException)

 

 

 


 

 

 

Spring의 트랜잭션 처리

 

1. 서비스클래스에서 메서드 레벨에 @Transactional 지정

(클래스 레벨에 지정하면 클래스 내의 모든 메서드가 트랜잭션으로 처리가 된다.)

@Transactional
public int insertxxx(DeptDTO dto){
	//DAO연동하면서 트랜잭션 처리 
	dao.insert(dto);
	dao.update(20);
}

@Transactional ⇒ insertxxx 메서드에서 수행된 DML 작업이 모두 성공하면 자동으로 commit하고
                              만약에 수행된 DML작업에서 하나라도 RuntimeException 이 발생되면 자동으로 rollback 처리됨.

 

 

 

 

2. @Transactional 활성화

https://docs.spring.io/spring-framework/docs/5.2.25.RELEASE/spring-framework-reference/data-access.html#transaction-declarative-annotations

 

Data Access

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies (such as JDBC, Hibernate, or JPA) in a consistent way. This lets you switch between the aforementioned persistence technologies fairly easily, a

docs.spring.io

 

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <!-- (this dependency is defined somewhere else) -->
     <property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>

또는

<bean id="transactionmanager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<tx:annotation-driven />

 

 

 


 

 

💻 실습

✅ 트랜잭션 처리X     예외X

 

 

 

✅ 트랜잭션 처리X     예외O

 

 

 

✅ 트랜잭션 처리O     예외O

 

 

'Framework > SPRING FRAMEWORK' 카테고리의 다른 글

Multi  (0) 2023.09.14
Spring MVC  (0) 2023.09.13
Spring에서의 MyBatis 연동  (1) 2023.08.31
(사용자가 만든) bean들을 등록없이 객체 생성하는 방법  (0) 2023.08.31
AOP_부가기능의 실행시점(advice) - @around  (0) 2023.08.31
xoo | 수진