设为首页 加入收藏

TOP

Spring声明式事务管理浅述
2018-03-02 06:57:12 】 浏览:131
Tags:Spring 声明 事务管理

首先我们先了解事务,什么是事务?


简单来说就是要么全部成功,要么什么都不做。


为什么要使用事务?


比如说常用银行系统的例子,如果没有用事务,有人在存入钱的时候出了问题,那么银行系统数据库的数据没有改变,但用户的钱却没了,这样就会出现很多问题。如果我们把整个存钱的过程看做一个事务,要么全部成功要么全部失败,这样就可以避免以上存在的问题。


声明式事务管理:


声明式事务管理也有两种常用的方式,一种是基于tx和aop名字空间的xml配置文件,另一种就是基于@Transactional注解。显然基于注解的方式更简单易用,更清爽。


先使用配tx和aop名字空间的xml配置文件


<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"></property>
    </bean>
   
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
        //以add、del、mod、开头的方法使用事务
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="mod*" propagation="REQUIRED" />
            <tx:method name="*" propagation="REQUIRED" read-only="true" />
        </tx:attributes>
    </tx:advice>


    <aop:config>
    //news.dao.*.*(..))意思是我们项目中news包下面的dao包下面所有类以及所有方法都可以引入事务管理。
        <aop:pointcut id="interceptorPointCuts"
            expression="execution(* 
        news.dao.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
    </aop:config>


这样我们配置完了以后只需要注意使用事务方法命名,当然如果没有注意命名空间又要使用事务,我们也可以新添加一个<tx:method>


使用@Transactional注解实现事务管理


@Override
        //该方法使用事务
    @Transactional(readOnly=true)
    public List showAllNews() {
        List<News> allNewList = nd.showAllNews();
        return allNewList;
    }


使用@Transactional注解,首先配置文件中无需配置tx:advice和aop:config,我们只需要在需要用事务的方法前面加@Transactional注解就可以了。


总结:两种方法各有优点,使用配置文件更好的解耦,换一个项目依然可以用,只需要该<tx:method name="del*">中的name的命名空间,和<aop:pointcut id="interceptorPointCuts" expression="execution(*news.dao.*.*(..))" />中execution()括号中的的命名。而使用@Transactional注解则更加简单直接,可读性更高。这里我建议大项目使用配置文件,小项目使用@Transactional注解。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇ViewPager中切换界面Fragment被销.. 下一篇Python中bisect的使用方法

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目