Connection conn = null; try{ conn = DBConnectionFactory.getConnection; conn.setAutoCommit(false); //do something conn.commit(); //commit transcation }catch(Exception e){ conn.rollback(); } finally{ try{ conn.close(); } catch(SQLException se){ //do sth.} //close ResultSet,PreparedStatement,Connection //notice:Maybe ocurr Exception when u close rs,pstmt,conn } |
TransactionDefinition td = new TransactionDefinition(); TransactionStatus ts = transactionManager.getTransaction(td); try{ //do sth transactionManager.commit(ts); }catch(Exception e){transactionManager.rollback(ts);} |
void add() { transactionTemplate.execute( new TransactionCallback(){ pulic Object doInTransaction(TransactionStatus ts) { //do sth} } } |
<bean id = "transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager"><ref bean="transactionManager"/></property> <property name="transactionAttributeSource"> <value> com.test.UserManager.*r=PROPAGATION_REQUIRED </value> </property> </bean> |
<bean id="userManager" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"><value>com.test.UserManager</value></property> <property name="interceptorNames"> <list> <idref local="transactionInterceptor"/> </list> </property> </bean> |
<bean id="userManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"><ref bean="transactionManager"/></property> <property name="target"><ref local="userManagerTarget"/></property> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> |