首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

spring引文的事务不开启

2012-12-28 
spring注解的事务不开启context:annotation-config /context:component-scan base-packagecom.shoppi

spring注解的事务不开启
<context:annotation-config /> 
    <context:component-scan base-package="com.shopping" /> 
    <!-- 采用注解形式的声明式事务管理 --> 
    <tx:annotation-driven transaction-manager="txManager"/> 
 
    <!-- 基于hibernate注解的sessionFactory --> 
    <bean id="sessionFactory" 
        value="classpath:hibernate.cfg.xml"> 
        </property> 
    </bean> 
    <!-- 基于hibernate的事务管理器 --> 
    <bean id="txManager" 
        ref="sessionFactory" /> 
    </bean> 
 
    <bean id="hibernateTemplate" ref="sessionFactory"></property> 
    </bean> 


这是applicationContext.xml的配置,但我在Service调用hibernateTemplate.getSessionFactory().getCurrentSession().createQuery("from Person");
这个方法的时候就报:org.hibernate.HibernateException: createQuery is not valid without active transaction
说事务没开启,但是我在方法上配置了@Transactional,@Transactional这个注解不会帮开事务的吗?

然后我用手动管理事务又OK了,不报错
                hibernateTemplate.getSessionFactory().getCurrentSession().beginTransaction();
hibernateTemplate.getSessionFactory().getCurrentSession().createQuery("from Person");
hibernateTemplate.getSessionFactory().getCurrentSession().getTransaction().commit();


这个问题很经典了
在住容器中,将Controller的注解排除掉
<context:component-scan base-package="com">
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

而在servlet的spring配置文件中将server给去掉
<context:component-scan base-package="com">
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
  </context:component-scan>

应为spring的context是父子容器,所以会产生冲突

如果这样还不对那就是其他问题了 呵呵 祝你好运

热点排行