1. 配置Spring3声明式事务
在Spring3中配置声明式事务比早期版本显得更加简便。只需要几行配置文件+注解就可以实现面向切面的AOP事务
2. 配置文件
在Spring的配置如下
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" default-autowire="byName"> <!-- 配置Spring上下文的注解 --> <context:annotation-config /> <!-- 配置DAO类 --> <bean id="persondao" class="impl.PersonDAOImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 事务管理配置 --> <!-- 配置事务管理开始 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="txManager" />在配置文件中并没有出现像以前版本的事务传播和隔离级别,也就是类似如下配置
<!-- 配置事务的传播特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="modify*" propagation="REQUIRED"/> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice>
因为可以通过注解@Transactional完成事务传播、事务隔离的功能。
3. DAO代码
DAO实现类代码如下
package impl; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.transaction.annotation.Transactional; import pojo.Test; @Transactional public class PersonDAOImpl extends HibernateDaoSupport implements PersonDAO { public void save(Test test) { this.getHibernateTemplate().saveOrUpdate(test); Test test2 = new Test(); test2.setId(3); test2.setName("3"); this.getHibernateTemplate().saveOrUpdate(test2); throw new RuntimeException("主键重复"); } }
使用注解将此DAO实现类的所有方法进行了事务拦截,当遇到运行是异常时,事务回滚。不提交到数据库。
当然可以指定单一原子方法进行隔离,方法可以指定
@Transactional(propagation=Propagation.NOT_SUPPORTED) @Transactional(propagation=Propagation.MANDATORY) @Transactional(propagation=Propagation.NESTED) @Transactional(propagation=Propagation.REQUIRED) @Transactional(propagation=Propagation.REQUIRES_NEW) @Transactional(propagation=Propagation.SUPPORTS)
同JTA标准的事务隔离传播一样,具体参考
http://suhuanzheng7784877.iteye.com/blog/908382
之后在Service层可以进行原子操作的业务整合。