SPRING - 스프링 트랜잭션(3)

이번 포스팅에선 이전 포스팅에서 사용한

트랜잭션 보다 좀더 사용하기 편한 방법을

알아보겠습니다. 플랫폼 트랜잭션 매니저 인터페이스 보다

더욱 많이 사용되는 방법 입니다. 먼저 servlet-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
50
51
52
53
54
55
56
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
 
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
 
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    
    <context:component-scan base-package="com.spring.ex" />
    <beans:bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <beans:property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
        <beans:property name="username" value="scott" />
        <beans:property name="password" value="tiger" />
    </beans:bean>
    
    <beans:bean name="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <beans:property name="dataSource" ref="dataSource" />
    </beans:bean>
    
    <beans:bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <beans:property name="dataSource" ref="dataSource" />
    </beans:bean>
    
    <beans:bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <beans:property name="transactionManager" ref="transactionManager"></beans:property>
    </beans:bean>
    
    <beans:bean name="dao" class="com.spring.ex.dao.TicketDao" >
        <beans:property name="template" ref="template" />
        <beans:property name="transactionTemplate" ref="transactionTemplate" />
    </beans:bean>
    
    
    <!-- <beans:bean name="dao" class="com.spring.ex.dao.TicketDao" >
        <beans:property name="template" ref="template" />
        <beans:property name="transactionManager" ref="transactionManager" />
    </beans:bean> -->
    
</beans:beans>
 
cs


40line의 트랜잭션템플릿을 새로 추가해줍니다

다음 44line 에서 방금 만든 트랜잭션템플릿을

레퍼런스로 참조합니다.

50line은 저번 포스팅에서 사용하던 소스입니다.


다음 DAO로 이동합니다


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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.spring.ex.dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
 
import com.spring.ex.dto.TicketDto;
 
public class TicketDao {
 
    JdbcTemplate template;
    
    //PlatformTransactionManager transactionManager;
    TransactionTemplate transactionTemplate;
    
    @Autowired
    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }
    
    /*public void setTransactionManager( PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }*/
    
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }
    
    public TicketDao() {
        System.out.println(template);
    }
    
    public void buyTicket(final TicketDto dto) {
        System.out.println("buyTicket()");
        System.out.println("dto.getConsumerId() : " + dto.getConsumerId());
        System.out.println("dto.getAmount() : " + dto.getAmount());
        
        //TransactionDefinition definition = new DefaultTransactionDefinition();
        //TransactionStatus status = transactionManager.getTransaction(definition);
        
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {        
        //try{
            
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus arg0) {
        template.update(new PreparedStatementCreator() {
            
            @Override
            public PreparedStatement createPreparedStatement(Connection con)
                    throws SQLException {
                String query = "insert into card (consumerId, amount) values (?, ?)";
                PreparedStatement pstmt = con.prepareStatement(query);
                pstmt.setString(1, dto.getConsumerId());
                pstmt.setString(2, dto.getAmount());
                
                return pstmt;
            }
        });
        
            template.update(new PreparedStatementCreator() {
            
                @Override
                public PreparedStatement createPreparedStatement(Connection con)
                        throws SQLException {
                String query = "insert into ticket (consumerId, countnum) values (?, ?)";
                PreparedStatement pstmt = con.prepareStatement(query);
                pstmt.setString(1, dto.getConsumerId());
                pstmt.setString(2, dto.getAmount());
                
                return pstmt;
                        }
            });
        }    
    });
        
        //transactionManager.commit(status);
        
    /*}catch(Exception e) {
        e.printStackTrace();
        
        transactionManager.rollback(status);
        
      }*/
    }
    
}
 
cs


21line에서 새로만든 트랜잭션 템플릿 객체를 생성하고

기존에 사용하던 20line의 플랫폼 트랜잭션매너지는

주석처리 하거나 지워줍니다. 

32line 에서는 스프링설정 파일에서만든 빈을 setter 해줍니다

45,46line역시 주석처리하거나 지워줍니다.

다음 트랜잭션을 처리하려고 try~catch문을 사용했던 부분

모두 주석처리 해줍니다.

48line을 새로추가합니다. 트랜잭션 발생시 결과값없이

트랜잭션을 callback합니다.

다음 트랜잭션 처리를 한 부분에 51~53line 을 사용하여

해당 부분을 감싸줍니다.


'SPRING' 카테고리의 다른 글

SPRING - Mybatis 사용하기(2)  (0) 2018.02.13
SPRING - Mybatis 사용하기(1)  (0) 2018.02.13
SPRING - 스프링 트랜잭션(2)  (0) 2018.02.08
SPRING - 스프링 트랜잭션(1)  (0) 2018.02.08
SPRING - 스프링JDBC, @Autowired  (0) 2018.02.08

댓글

Designed by JB FACTORY