需要事务处理的方法:
该方法所在类不需要实现任何接口!!
public class aservers{
@Autowired private DeptDAO deptopt;//spring 来完成deptopt的初始化 不需要写getter setter
public void insertDemoData() throws Exception{//一定不要自己catch抛出异常,否则不能回滚
Dept dept1=new Dept(); dept1.setName("事业部");
deptopt.save(dept1);
int i=1/0; //异常
}
}
spring 配置文件:
<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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"><!-- 定义切面 -->
<aop:config>
<aop:pointcut id="serviceOperation"<!-- 模糊匹配需要拦截的包 -->
expression="execution(*com.casw.ssh.dept.actions.*.*(..))"/>
<aop:advisorpointcut-ref="serviceOperation"advice-ref="txAdvice"/>
</aop:config>
<!--定义需要管理的方法-->
<tx:adviceid="txAdvice"transaction-manager="transactionManager">
<tx:attributes><!-- 模糊匹配需要拦截的方法 -->
<tx:methodname="find*"read-only="true"/>
<tx:methodname="insert*"/>
</tx:attributes>
</tx:advice>
<!--定义事务管理器,使用适用于Hibernte的事务管理器-->
<beanid="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<!--HibernateTransactionManagerbean需要依赖注入一个SessionFactorybean的引用-->
<propertyname="sessionFactory">
<reflocal="sessionFactory"/>
</property>
</bean>
<!--其他配置略-->
OK 配置完毕, 出异常的话就会回滚,注释掉 int i=1/0, 就会更新数据库。
其实这样配置的最大好处就是aservers不需要 实现什么接口了,