解决 spring mvc 3.0 结合 hibernate3.2 使用<tx:annotation-driven>声明式事务无法提交的问题

看了半天,也不知道这篇文章在说什么,后来想应该是这位仁兄把<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />放在application.xml中,而<context:component-scan base-package="com.fengzhiyin" />spring-servlet.xml,要放就要放在一起

1、问题复现

spring 3.0 + hibernate 3.2
spring mvc使用注解方式;service使用@service注解 事务使用@Transactional

事务配置使用

    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />  

在插入或更新数据时,无报错,但数据库中无结果,而查询正常。疑为事务未提交。

2、问题检查

当修改dao层实现逻辑为:

    Assert.notNull(entity, "entity不能为空");  
    Transaction ts = getSession().beginTransaction();  
    getSession().saveOrUpdate(entity);  
    getSession().flush();  
    ts.commit();  
    logger.debug("save entity: {}", entity);  

可以正常提交插入、更新。确定为事务未提交。

3、问题分析

spring mvc使用注解方式时需要使用

    <context:component-scan base-package="com.fengzhiyin" />  

方式用来扫描该包以及其子包下的@Controller注解的类,纳入spring管理,而同时spring容器也需要使用这种方式扫描包含@Service@Components@Required@Autowired等注解用来管理bean和完成DI。

    <context:component-scan base-package="com.fengzhiyin" />  

出现在spring mvc的配置文件中时,web 容器在扫描包含@Service@Components的类并包含@Transaction时,此时@Transaction并未完成,导致事务未被注册。

4、问题解决

将spring mvc中扫描controller的context:component分成两部分,将扫描其他目录的context:component放入application.xml文件中(该文件为)org.springframework.web.context.ContextLoaderListener的加载文件。

    <!-- spring mvc 配置文件 -->  
    <context:component-scan base-package="com.fengzhiyin.controller" />  

    <!-- spring context配置文件 -->  
    <context:component-scan base-package="com.fengzhiyin.">  
        <context:exclude-filter type="regex" expression=".*Controller$" />  
    </context:component-scan>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值