[스프링3.X, 마이바티스]Transaction 처리예제,Spring3.X, MyBatis3.X
Spring 의 Transaction Manager 를 사용하여 트랜잭션 처리
Spring 에서 제공해주는 Transaction Manager 기능으로 서비스 영역까지 트랜잭션을 처리할 수 있는 편리한 트랜잭션
처리 방식이다.
이전 MyBatis로 구현한 Customer 예제에 Transaction을 적용하자.
1. Customer.java
package onj.edu.jdbc3;
public class Customer {
private Integer
id;
private String
name;
private Integer
age;
public Integer
getId() {
return id;
}
public void
setId(Integer id) {
this.id =
id;
}
public String
getName() {
return
name;
}
public void
setName(String name) {
this.name =
name;
}
public Integer
getAge() {
return
age;
}
public void
setAge(Integer age) {
this.age =
age;
}
}
2. CustomerDao.java
package onj.edu.jdbc3;
import java.util.List;
import onj.edu.jdbc3.Customer;
public interface CustomerDao {
public int
createCustomer(Customer customer);
public int
deleteCustomer(Customer customer);
public int
updateCustomer(Customer customer);
public Customer
getCustomer(Integer id);
public
List<Customer> getListCustomer();
}
3. CustomerDaoImpl.java
package onj.edu.jdbc3;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import onj.edu.jdbc3.Customer;
public class CustomerDaoImpl implements CustomerDao {
@Resource(name =
"sqlSession")
private
SqlSession sqlSessionTemplate;
@Override
public int
createCustomer(Customer customer) {
CustomerDao
customerDao = sqlSessionTemplate
.getMapper(CustomerDao.class);
return
customerDao.createCustomer(customer);
}
@Override
public Customer
getCustomer(Integer id) {
CustomerDao
customerDao = sqlSessionTemplate
.getMapper(CustomerDao.class);
return
customerDao.getCustomer(id);
}
@Override
public
List<Customer> getListCustomer() {
@SuppressWarnings("unchecked")
List<Customer>
list = (List<Customer>) sqlSessionTemplate
.getMapper(CustomerDao.class);
return
list;
}
@Override
public int
deleteCustomer(Customer customer) {
CustomerDao
customerDao = sqlSessionTemplate
.getMapper(CustomerDao.class);
return
customerDao.deleteCustomer(customer);
}
@Override
public int
updateCustomer(Customer customer) {
CustomerDao
customerDao = sqlSessionTemplate
.getMapper(CustomerDao.class);
return
customerDao.updateCustomer(customer);
}
}
4. CustomerTest.java
(이클립스에서 run as --> JUnit Test로 실행하자)
package onj.edu.jdbc3;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import
org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import
org.springframework.transaction.support.DefaultTransactionDefinition;
import onj.edu.jdbc3.CustomerDao;
import onj.edu.jdbc3.Customer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations =
"classpath:context/appcontext-mybatis3.xml")
public class CustomerTest {
@Autowired
private
CustomerDao customerDao;
@Autowired
private
PlatformTransactionManager transactionManager;
DefaultTransactionDefinition def = null;
TransactionStatus
status = null;
//PlatformTransactionManager
이용 수동으로 트랜잭션을 다루는 방법
@Test
public void
test() {
try {
def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
status
= transactionManager.getTransaction(def);
Customer
customer = new Customer();
customer.setAge(30);
customer.setId(30);
customer.setName("오엔제이30");
int cnt =
customerDao.createCustomer(customer);
System.out.println("<<<<< 30번 Insert OK");
customer.setId(31);
cnt =
customerDao.createCustomer(customer);
System.out.println("<<<<< 31번 Insert OK");
customer.setId(32);
cnt =
customerDao.createCustomer(customer);
System.out.println("<<<<< 32번 Insert OK");
customer = new
Customer(); customer.setAge(99);
customer.setId(30);
customer.setName("30번
새이름:오라클자바커뮤니티");
cnt =
customerDao.updateCustomer(customer);
System.out.println(">>>>> 3번 Update OK ---> " +
cnt);
customer = new
Customer();
customer.setId(31);
int deleteCnt =
customerDao.deleteCustomer(customer);
System.out.println("삭제건수 = " + deleteCnt);
System.out.println(">>>>> 31번 Delete OK");
transactionManager.commit(status);
} catch
(Exception e) {
transactionManager.rollback(status);
}
}
}
5. appcontext-mybatis3.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 스프링 트랜잭션을 가능하게 하려면 DataSourceTransactionManager를 생성
-->
<bean
id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property
name="dataSource" ref="dataSource" />
</bean>
<!--
마이바티스는 스프링 트랜잭션 리소스처럼 동작,스프링은 이미 설정된 트랜잭션을
사용해서
SqlSession을 동작중인 트랜잭션에 넣는다. -->
<tx:annotation-driven
/>
<bean
id="dataSource"
class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property
name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
<property
name="url" value="jdbc:oracle:thin:@192.168.0.85:1521:onj" />
<property
name="username" value="scott" />
<property
name="password" value="tiger" />
</bean>
<bean
id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property
name="dataSource" ref="dataSource" />
<property
name="configLocation" value="classpath:mybatis/sqlmap-config3.xml" />
<property
name="mapperLocations" value="classpath:mybatis/mappers/customer3.xml"
/>
</bean>
<bean
id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg
index="0" ref="sqlSessionFactory" />
</bean>
<bean
id="customerDao" class="onj.edu.jdbc3.CustomerDaoImpl" />
</beans>
6. sqlmap-config3.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias
type="onj.edu.jdbc3.Customer"
alias="customer" />
</typeAliases>
</configuration>
7. customer3.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="onj.edu.jdbc3.CustomerDao">
<resultMap type="customer" id="customerid">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="age" column="age" />
</resultMap>
<select id="getCustomer" parameterType="int"
resultMap="customerid">
SELECT * FROM CUSTOMER WHERE ID = #{id}
</select>
<insert id="createCustomer"
parameterType="onj.edu.jdbc3.Customer">
INSERT INTO CUSTOMER(ID, NAME, AGE) VALUES (#{id},#{name},#{age})
</insert>
<update id="updateCustomer"
parameterType="onj.edu.jdbc3.Customer">
UPDATE CUSTOMER
SET AGE = #{age},
NAME = #{name}
WHERE
ID = #{id}
</update>
<delete id="deleteCustomer"
parameterType="onj.edu.jdbc3.Customer">
DELETE FROM CUSTOMER WHERE ID = #{id}
</delete>
</mapper>
8. 결과
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from class path resource
[context/appcontext-mybatis3.xml]
INFO : org.springframework.context.support.GenericApplicationContext -
Refreshing org.springframework.context.support.GenericApplicationContext@e94c62:
startup date [Tue Oct 08 21:10:54 KST 2013]; root of context hierarchy
INFO :
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
- JSR-330 'javax.inject.Inject' annotation found and supported for
autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory
- Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@1e90d95:
defining beans
[transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,dataSource,sqlSessionFactory,sqlSession,customerDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor];
root of factory hierarchy
<<<<< 30번 Insert OK
<<<<< 31번 Insert OK
<<<<< 32번 Insert OK
>>>>> 3번 Update OK ---> 2
삭제건수 = 1
>>>>> 31번 Delete OK
INFO : org.springframework.context.support.GenericApplicationContext -
Closing org.springframework.context.support.GenericApplicationContext@e94c62:
startup date [Tue Oct 08 21:10:54 KST 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory
- Destroying singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@1e90d95:
defining beans
[transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,dataSource,sqlSessionFactory,sqlSession,customerDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor];
root of factory hierarchy
9. customer Table Select 결과
SQL> select * from customer;
ID NAME
---------- -----------------------
30 30번 새이름:오라클자바커뮤니티
32 3길동
[개강확정강좌]오라클자바커뮤니티에서 운영하는 개발자 전문교육 ,개인80%환급(www.onjprogramming.co.kr)
[주말]
[10/26]C#,ASP.NET마스터
[11/2]Spring3.X, MyBatis, Hibernate실무과정
[11/2]JAVA&WEB프레임워크실무과정
[평일야간]
[10/29]C#,ASP.NET마스터
[10/31]JAVA&WEB프레임워크실무과정
[11/1]Spring3.X, MyBatis, Hibernate실무과정
[주간]
[11/4]Spring3.X, MyBatis, Hibernate실무과정
[주말]
[10/26]C#,ASP.NET마스터
[11/2]Spring3.X, MyBatis, Hibernate실무과정
[11/2]JAVA&WEB프레임워크실무과정
[평일야간]
[10/29]C#,ASP.NET마스터
[10/31]JAVA&WEB프레임워크실무과정
[11/1]Spring3.X, MyBatis, Hibernate실무과정
[주간]
[11/4]Spring3.X, MyBatis, Hibernate실무과정
[기타
다른 강좌는 아래 해당 카테고리를 클릭해주세요]
댓글 없음:
댓글 쓰기