MVC_Spring - 트랜잭션 기본
프로그래밍 정리/Spring
2020. 1. 3. 13:09
반응형
MVC_Spring - 트랜잭션 기본
- 트랜잰션이란?
- 트랜잭션 간단히 정리
간단히 얘기하자면 트랜잭션은 하나의 작업단위이다.
예를들면 쿼리문 insert into ~ 을 실행하는 순간부터
Data Base에 저장이 완료되기까지를
하나의 작업단위라고 생각하면 된다.
- 트랜잭션 오류 처리
서로 연관된 2개의 트랜잭션을 처리할때
하나라도 오류가 생긴다면
전부 다 롤백 되어야한다.
- 사용되는 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 | //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> //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 |
- 실습예제
실습예제를 보기전에 SQL Template를 잊어버렸다면
참고하세요 ( 링크 : https://cloud0477.tistory.com/76 )
-TicketDao.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 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 | public class TicketDao { JdbcTemplate template; PlatformTransactionManager transactionManager; public void setTemplate(JdbcTemplate template) { this.template = template; } public void setTransactionManager( PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } 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); //트랜잭션매니저에서 트랜잭션을 가져온다. try { 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); //정상적으로 처리가 되었으면 Commit } catch (Exception e) { e.printStackTrace(); transactionManager.rollback(status); //비정상적으로 에러가 나면 Rollback } } } | 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 |