事务管理在java开发过程中很常见,实现方式也很多,其中,spring事务管理使用起来比较方便,现就其汇总如下:
1、配置文件:
将spring框架中的事务管理引入进具体的实现类
<bean id="xlTransactionManagerService" class="com.xl.service.XlTransactionManagerService">
<property name="theDao" ref="theDao" />
<property name="xlTransactionManager" ref="xlTransactionManager" />
</bean>
<bean id="xlDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:/jdbc/xlDB</value>//jboss数据库
</property>
</bean>
<bean id="xlTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="xlDataSource" />
</property>
</bean>
<bean id="xlTransactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="xlTransactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,-Exception</prop>
</props>
</property>
</bean>
2、具体的事务实现
public class XlTransactionManagerService {
private XXXDao theDao;
private PlatformTransactionManager transactionManager;
get/set 方法
public void transactionMethod() {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
try {
this.theDao().method1();
this.theDao().method2();
transactionManager.commit(status);
} catch (DAOException e) {
System.out.println("数据库操作失败:");
transactionManager.rollback(status); // 事务回滚
e.printStackTrace();
}
}
}
1、配置文件:
将spring框架中的事务管理引入进具体的实现类
<bean id="xlTransactionManagerService" class="com.xl.service.XlTransactionManagerService">
<property name="theDao" ref="theDao" />
<property name="xlTransactionManager" ref="xlTransactionManager" />
</bean>
<bean id="xlDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:/jdbc/xlDB</value>//jboss数据库
</property>
</bean>
<bean id="xlTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="xlDataSource" />
</property>
</bean>
<bean id="xlTransactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="xlTransactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,-Exception</prop>
</props>
</property>
</bean>
2、具体的事务实现
public class XlTransactionManagerService {
private XXXDao theDao;
private PlatformTransactionManager transactionManager;
get/set 方法
public void transactionMethod() {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
try {
this.theDao().method1();
this.theDao().method2();
transactionManager.commit(status);
} catch (DAOException e) {
System.out.println("数据库操作失败:");
transactionManager.rollback(status); // 事务回滚
e.printStackTrace();
}
}
}