Spring4+Hibernate4声明式事务管理

来源:互联网 发布:时时彩模拟软件 编辑:程序博客网 时间:2024/06/06 12:22

具体配置见之前的文章 http://blog.csdn.net/qq_17632417/article/details/77127191

首先要说明的是,事务是在Service层管理,而不是在DAO层。
声明式事务不需要在代码中开启事务或者事务回滚,一切都在xml文件里搞定。
我感觉这样做有点不方便。不过这是一种很好的代码规范(据说)

简单贴事务重点部分代码

<!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="test*" propagation="REQUIRED" />            <tx:method name="*" propagation="REQUIRED" />        </tx:attributes>    </tx:advice>    <!-- rollback-for="java.io.IOException" -->    <!-- 只对业务逻辑层实施事务 -->    <aop:config expose-proxy="true">         <aop:pointcut id="txPointcut"            expression="execution(* com.ghy.service..*.*(..))" />        <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice -->        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />    </aop:config>

声明式事务只会处理RuntimeException及其子类、Error。
如NullPointerException、ArithmeticException。并且不能Catch。
e.g.
DAO层

public void test()  {        Session session = getSession();        session.createSQLQuery("INSERT INTO t_orders VALUES(null,1)").executeUpdate();            int a  = 1/0;    }

Service层

public void test() {        try {            testDaoImpl.test();        } catch (ArithmeticException e) {        }     }

这样做,事务是不会回滚的,想让事务回滚那就要将Catch去掉
Service层

public void test() {    testDaoImpl.test();}

另外,如果想让checked Exception发生时,如IOException,事务也回滚的话,需要在Catch里面再进行throw new RuntimeException(),这样做感觉有点弱智?
e.g.
DAO层

public void test() throws IOException  {        Session session = getSession();        session.createSQLQuery("INSERT INTO t_orders VALUES(null,1)").executeUpdate();        throw new IOException();    //抛出一个IO异常    }

Service层

public void test() {            try {                testDaoImpl.test();            } catch (IOException e) {                throw new RuntimeException();            }    }
原创粉丝点击