码迷,mamicode.com
首页 > Web开发 > 详细

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

时间:2015-02-03 16:33:33      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:

public void save(BaseEntity baseEntity) {
        Session session = null;
        try {
            session = currentSession();
            session.save(baseEntity);
        } catch (HibernateException ex) {
            ex.printStackTrace();
        } 
    }

当我执行该save方法时,抛出了该异常。

问题分析:

没有配置事务引起的问题。

解决办法:

我采用的是注解配置事务的方式,在XXX-servlet.xml中加上:

<tx:annotation-driven/>
<!-- <tx:annotation-driven transaction-manager="XXX"/> -->

 

这样就支持注解的方式配置事务了,这个标签会默认选择id为transactionManager的事务管理器(可以通过修改其transaction-Manager属性值来指定其他事务管理器)。

然后在application-config.xml(数据库的spring配置文件,即配置sessionFactory的地方)中加上:

<!-- 事务 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean> 

就成功配置事务了。

然后在需要使用事务的方法上加上@Transactional就能解决异常抛出的问题了。

@Transactional
public void save(BaseEntity baseEntity) {
        Session session = null;
        try {
            session = currentSession();
            session.save(baseEntity);
        } catch (HibernateException ex) {
            ex.printStackTrace();
        } 
    }

 

(在类级加上@Transactional好像会出其他的错误,有待进一步调试...)

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

标签:

原文地址:http://www.cnblogs.com/SunseCode/p/4270137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!