Spring Transaction

spring 推荐使用

public void save(Good good) {
        this.sessionFactory.getCurrentSession().save(good);
    }

以上编写dao代码,推荐使用hibernateTemplate,避免框架的入侵。这种方式如果不配置事务管理

<!--<aop:config>-->
        <!--<aop:pointcut id="goodServiceMethods" expression="execution(* cn.bb.service.GoodService.*(..))"/>-->
        <!--<aop:advisor advice-ref="txAdvice" pointcut-ref="goodServiceMethods"/>-->
    <!--</aop:config>-->

    <!--<tx:advice id="txAdvice" transaction-manager="transactionManager">-->
        <!--<tx:attributes>-->
            <!--<tx:method name="increasePrice*" propagation="REQUIRED"/>-->
            <!--<tx:method name="save*" propagation="REQUIRED"/>-->
            <!--<tx:method name="*" propagation="SUPPORTS" read-only="true"/>-->
        <!--</tx:attributes>-->
    <!--</tx:advice>-->

就会抛出异常

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here


如果不注释上面的代码则程序能正常运行。

public void saveGoodBatch(List<Good> goodList) throws Exception{
        for(Good good : goodList) {
            saveGood(good);
//            goodDao.save(good); //都行
        }
//        throw new Exception("sss"); //不会回滚
        throw new RuntimeException("aa"); //会回滚
    }


在service已经配置了事务的方法中 使用throw new Exception() 不会导致事务回滚;使用throw new RuntimeException 就会导致事务回滚,至于方法中是直接调用dao的还是service中无所谓。

Spring Transaction,布布扣,bubuko.com

Spring Transaction

上一篇:Java 判断操作系统类型(适用于各种操作系统)


下一篇:python 之双色球预测