트랜잭션(Transaction) 이란
프로그램 개발을 하다보면 쿼리 한줄로 해결할 수 없는 로직을 처리해야 하는 경우가 정말 많이 생긴다.
하나의 메소드(method) 에서 여러 개의 쿼리가 실행해야 하는 경우 전부 정상적으로 실행이 되면 문제가 없겠지만 중간에 어느 하나의 쿼리에서 오류나 문제가 생긴다면 시스템에 큰 문제가 생길수 있다. 그때 정상적으로 실행이 된다면 사용했던 쿼리를 commit 하고 만약 문제가 생긴다면 다시 rollback 을 하기때문에 문제가 생기더라도 조금 덜 걱정할 수 있다.
JAVA에서 트랜잭션을 처리하려면 context-transaction.xml 과 JAVA 소스 수정이 조금 필요하다.
나는 전자정부프레임워크를 사용하다 보니 src/main/resources/egovframework/spring/com 경로에 context-transaction.xml 가 있어서 별도의 생성을 할 필요는 없었다.
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="egov.dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="requiredTx" expression="execution(* egovframework.com..*Impl.*(..)) or
execution(* egovframework.rte.fdl.excel.impl.*Impl.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="requiredTx" />
</aop:config>
</beans>
위와 같이 context-transaction.xml 가 있다면 바로 자바 코드를 수정할 수 있다. 방법은 어렵지 않다.
- 클래스명 아래에
@Resource(name = "txManager")
protected DataSourceTransactionManager txManager;
를 입력 해 준다. - 실행이 필요한 메소드 안쪽에
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus txStatus = txManager.getTransaction(def);
를 입력 해 준다. - try 안에 실행할 여러 쿼리들을 작성해 준후 try 제일 마지막 부분에 정상적으로 실행이 된다면 commit을 할수 있도록 txManager.commit(txStatus); 을 작성해준다.
- catch 안에는 try와 반대로 정상적으로 실행이 되지 않았을 경우 에러 로그와 rollback 을 진행하기 위하여
e.printStackTrace();
txManager.rollback(txStatus); 를 작성해 준다.
'개발 > BackEnd' 카테고리의 다른 글
내가 보려고 쓰는 페이징유틸(PagingUtil) (1) | 2023.12.27 |
---|---|
XSSFDrawing 사용 엑셀 메모박스 만들기 (0) | 2023.04.28 |
poi HSSF 사용시 Excel DropDownListBox 사용 (java 엑셀 드롭다운, 셀렉트박스) (0) | 2023.04.28 |
The maximum column width for an individual cell is 255 characters. 엑셀 다운로드시 Error (0) | 2021.10.01 |