`
zhaohaolin
  • 浏览: 984454 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

MyBatis3整合Spring3的Transaction事务处理

阅读更多

正如第二版,Spring 仅支持 iBatis2。那么我们就想将 MyBatis3 的支持加入到 Spring3.0(参考 Spring 的 Jira 的问题)中。

不幸的是,Spring 3.0 的开发在 MyBatis 3.0 官方发布前就结束了。因为Spring开发团队不想发布一个基于非发行版的MyBatis的整合支持,

那么 Spring官方的支持就不得不等到至少 3.1 版本了。要在 Spring 中支持 MyBatis,MyBatis 社区认为现在应该是自己团结贡献者和有兴趣的人

一起来开始进行 Spring 和 MyBatis 整合的时候了。 这个小类库就来创建丢失的粘贴 Spring 和 MyBtatis 这两个流行框架的胶水。

减少用户不得不来配置MyBatis和Spring 3.X上下文环境的样板和冗余代码。 它还透明地增加了 Spring对 MyBatis 事务的支持。

      所以尽管MyBatis3提供了对Spring的整合,但是org.springframework.jdbc.datasource.DataSourceTransactionManager这个事务管理器还是不支持

aop的事务管理方式,如果你还想设置你的事务的隔离级别、只读(PROPAGATION_REQUIRED、ISOLATION_DEFAULT、readOnly、timeout)。

那么你可以使用org.springframework.transaction.interceptor.TransactionProxyFactoryBean这个事务拦截器的代理工厂。它还是可以完成的,但是当然不会

有HibernateTransactionManager那样的完美,因为DataSourceTransactionManager不能使用aop来管理我们的事务。

基本配置如下:

<!-- 配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了 -->
<
bean
 id
="transactionManager"
 class
="org.springframework.jdbc.datasource.DataSourceTransactionManager"
>
    <
property
 name
="dataSource"
 ref
="dataSource"
 />
</
bean
>
 
<!-- 配置事务的传播特性 -->
<
bean
 id
="baseTransactionProxy"
 class
="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
 abstract
="true"
>
    <
property
 name
="transactionManager"
 ref
="transactionManager"
 />
    <
property
 name
="transactionAttributes"
>
        <
props
>
            <
prop
 key
="add*"
>
PROPAGATION_REQUIRED</
prop
>
            <
prop
 key
="edit*"
>
PROPAGATION_REQUIRED</
prop
>
            <
prop
 key
="remove*"
>
PROPAGATION_REQUIRED</
prop
>
            <
prop
 key
="insert*"
>
PROPAGATION_REQUIRED</
prop
>
            <
prop
 key
="update*"
>
PROPAGATION_REQUIRED</
prop
>
            <
prop
 key
="del*"
>
PROPAGATION_REQUIRED</
prop
>
            <
prop
 key
="*"
>
readOnly</
prop
>
        </
props
>
    </
property
>
</
bean
>

然后,你需要配置的是对那个类的进行拦截器事务管理,就就需要设置这个接口的parent属性为baseTransactionProxy,target是该接口的实现类。如下:

<!-- 为AccountBiz接口配置事务拦截器,baseTransactionProxy是事务拦截器,在Controller中获取这个对象 -->
<
bean
 id
="accountBiz"
 parent
="baseTransactionProxy"
>
    <!-- 设置target,也就是AccountBiz的实现类 -->
    <
property
 name
="target"
 ref
="accountBizImpl"
/>
</
bean
>

上面的accountBiz是一个接口,它的实现类的id是accountBizImpl。然后你在Struts或SpringMVC中注入accountBiz这个接口即可使用里面的方法了。

糟糕的是,你需要为所有需要事务管理的类或接口都要进行这个配置!也许你可以配置一个BaseBiz的parent是baseTransactionProxy,然后所有要进行

事务管理的接口或类,继承或实现BaseBiz这个接口。不妨可以尝试一番!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics