Hibernate4 No Session found for current thread缘由

Hibernate4 与 spring3 集成以后, 若是在取得session 的地方使用了getCurrentSession, 可能会报一个错:“No Session found for current thread”, 这个错误的缘由,网上有不少解决办法, 但具体缘由的分析,却没有多少, 这里转载一个原理分析:

SessionFactory的getCurrentSession并不能保证在没有当前Session的状况下会自动建立一个新的,这取决于CurrentSessionContext的实现,SessionFactory将调用CurrentSessionContext的currentSession()方法来得到Session。在Spring中,若是咱们在没有配置TransactionManager而且没有事先调用SessionFactory.openSession()的状况直接调用getCurrentSession(),那么程序将抛出“No Session found for current thread”异常。若是配置了TranactionManager而且经过@Transactional或者声明的方式配置的事务边界,那么Spring会在开始事务以前经过AOP的方式为当前线程建立Session,此时调用getCurrentSession()将获得正确结果。

然而,产生以上异常的缘由在于Spring提供了本身的CurrentSessionContext实现,若是咱们不打算使用Spring,而是本身直接从hibernate.cfg.xml建立SessionFactory,而且为在hibernate.cfg.xml
中设置current_session_context_class为thread,也即便用了ThreadLocalSessionContext,那么咱们在调用getCurrentSession()时,若是当前线程没有Session存在,则会建立一个绑定到当前线程。

Hibernate在默认状况下会使用JTASessionContext,Spring提供了本身SpringSessionContext,所以咱们不用配置current_session_context_class,当Hibernate与Spring集成时,将使用该SessionContext,故此时调用getCurrentSession()的效果彻底依赖于SpringSessionContext的实现。

在没有Spring的状况下使用Hibernate,若是没有在hibernate.cfg.xml中配置current_session_context_class,有没有JTA的话,那么程序将抛出"No CurrentSessionContext configured!"异常。此时的解决办法是在hibernate.cfg.xml中将current_session_context_class配置成thread。

在Spring中使用Hibernate,若是咱们配置了TransactionManager,那么咱们就不该该调用SessionFactory的openSession()来得到Sessioin,由于这样得到的Session并无被事务管理。

至于解决的办法,能够采用以下方式:
1.  在spring 配置文件中加入
java

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


而且在处理业务逻辑的类上采用注解 spring

注:@Transactional能够注解在方法上也能够注解到类上,注解到类上全部方法都使用事物管理 session

@Service


public class CustomerServiceImpl implements CustomerService {  
    @Transactional
    public void saveCustomer(Customer customer) {
        customerDaoImpl.saveCustomer(customer);
    }
    ...
}
@Service

@Transactional

public class CustomerServiceImpl implements CustomerService {  
    public void saveCustomer(Customer customer) {
        customerDaoImpl.saveCustomer(customer);
    }
    ...
}



另外在 hibernate 的配置文件中,也能够增长这样的配置来避免这个错误: spa

注:spring管理不须要添加这个
hibernate

 <property name="current_session_context_class">thread</property>
相关文章
相关标签/搜索