[Spring] 트랜잭션 관리

 비즈니스에서 어느 특정한 기능은 한 개 이상으로 작업의 단위로 구성된다.

대체적으로 두 개 이상의 작업으로 구성되는 일이 잦으며, 이때의 기능은 반드시 하나의 작업처럼 진행되어야 한다. 둘 중 하나의 작업만 수행되서는 안되며, 수행 후 일관성의 유지, 외부에서의 간섭 등이 있어서는 안된다.

이때 수행 후 그 결과는 영속성을 띄어야 한다.

 

※ bankTransfer() 메소드에 두 개의 메소드가 동작한다면,
두 메소드 모두가 완전히 수행되어야 한다.

- pom.xml
-트랜잭션 응용을 위한 Maven


- root-context.xml 설정 사항
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://mybatis.org/schema/mybatis-spring
    http://mybatis.org/schema/mybatis-spring.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
    
    <context:annotation-config></context:annotation-config>
    <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:hr" />
        <property name="username" value="user명" /> <!-- user 이름 -->
        <property name="password" value="패스워드" /> <!-- 패스워드 -->
    </bean>
    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 트랜잭션 관리 bean -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <tx:annotation-driven/>
    
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
        <constructor-arg ref="hikariConfig" />
    </bean>
    
    <mybatis:scan base-package="com.test.mapper" />
    
    <context:component-scan base-package="com.test.service"></context:component-scan>
    <context:component-scan base-package="com.test.aop"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
</beans>
 
cs


- 적용 방법
- 원자성 등의 트랜잭션의 특성이 요구되는 메소드에 @Transactional 을 기재
- 해당 어노테이션이 적용되는 메소드에서 수행되는 여러 SQL 중 하나 이상 오류 발생 시 원자성을 유지한다(다른 SQL 수행이 Rollback 됨)



댓글