MVC_Spring - 트랜잭션 템플릿 사용
프로그래밍 정리/Spring
2020. 1. 3. 18:00
반응형
MVC_Spring - 트랜잭션 템플릿 사용
실제로 자주사용하는 트랜잭션 템플릿이다.
※트랜잭션 기본개념을 알고 싶다면 다음 링크를 확인하세요
- 사용되는 Dependency
- spring-jdbc release 4.1.4
- 사용되는 import
1 2 3 4 5 | 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; | cs |
- 필요한 설정
-pom.xml
-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 | //Connection Pull 이용하기 위한 초기화 <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> //템플릿 객체 초기화 : DataSource(Connection Pull이용)를 넣어준다 <beans:bean name="template" class="org.springframework.jdbc.core.JdbcTemplate"> <beans:property name="dataSource" ref="dataSource" /> </beans:bean> //트랜잭션매니저 객체 초기화 : DataSource(Connection Pull이용)를 넣어준다 <beans:bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <beans:property name="dataSource" ref="dataSource" /> </beans:bean> //트랜잭션템플릿 객체 초기화 : 위에서 만든 transactionManager 넣어준다. <beans:bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <beans:property name="transactionManager" ref="transactionManager"></beans:property> </beans:bean> //DAO 객체 초기화 : 위에서 만든 template, transactionManager 넣어준다. <beans:bean name="dao" class="com.javalec.spring_pjt_ex.dao.TicketDao" > <beans:property name="template" ref="template" /> <beans:property name="transactionManager" ref="transactionManager" /> </beans:bean> | cs |
- 실습 예제
-TicketDao
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 | package com.javalec.spring_pjt_ex.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; 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.javalec.spring_pjt_ex.dto.TicketDto; public class TicketDao { //DB 쿼리를 위한 JDBC 템플릿 JdbcTemplate template; //트랜잭션을 위한 트랜잭션 템플릿 TransactionTemplate transactionTemplate; public void setTemplate(JdbcTemplate template) { this.template = template; } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } public void buyTicket(final TicketDto dto) { System.out.println("buyTicket()"); System.out.println("dto.getConsumerId() : " + dto.getConsumerId()); System.out.println("dto.getAmount() : " + dto.getAmount()); transactionTemplate.execute(new TransactionCallbackWithoutResult() { //트랜잭션 템플릿사용 //성공시 자동으로 commit; //실패시 자동으로 rollback; //하나의 트랜잭션으로 무 @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; } }); } }); } } | cs |
-Controller.java
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 | @Controller public class HomeController { private TicketDao dao; @Autowired public void setDao(TicketDao dao) { this.dao = dao; } private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping("/buy_ticket") public String buy_ticket() { return "buy_ticket"; } @RequestMapping("/buy_ticket_card") public String buy_ticket_card(TicketDto ticketDto, Model model) { System.out.println( "buy_ticket_card" ); System.out.println( "ticketDto : " + ticketDto.getConsumerId() ); System.out.println( "ticketDto : " + ticketDto.getAmount() ); dao.buyTicket(ticketDto); model.addAttribute("ticketInfo", ticketDto); return "buy_ticket_end"; } } | cs |
-TicketDto.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class TicketDto { private String consumerId; private String amount; public String getConsumerId() { return consumerId; } public void setConsumerId(String consumerId) { this.consumerId = consumerId; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } } | cs |
-buy_ticket.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <p>카드 결제</p> <form action="buy_ticket_card"> 고객 아이디 : <input type="text" name="consumerId" > <br /> 티켓 구매수 : <input type="text" name="amount" > <br /> <input type="submit" value="구매" > <br /> </form> </body> </html> | cs |
-buy_ticket_end.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> buy_ticket_end.jsp 입니다. <br /> ${ticketInfo.consumerId } <br /> ${ticketInfo.amount } <br /> </body> </h | cs |
반응형
'프로그래밍 정리 > Spring' 카테고리의 다른 글
MVC_Spring - 트랜잭션 전파속성 (0) | 2020.01.07 |
---|---|
MVC_Spring - 트랜잭션 기본 (0) | 2020.01.03 |
MVC_Spring - @Autowired 사용하기 (0) | 2020.01.03 |
MVC_Spring - JDBC 템플릿 사용하기 (0) | 2020.01.02 |
MVC_Spring - 폼 데이터 값 검증 (0) | 2020.01.02 |