Skip to main content
 首页 » 编程设计

spring之如何在线程中访问 hibernate session

2025年01月19日20pengyingh

由于 Hibernate session 不是线程安全的,我无法通过 sessionFactory.getCurrentSession() 获取当前的 hibernate session ;

如果我选择 sessionFactory.openSession();它适用于线程本身,但对于嵌套类[从线程调用],它不允许我访问同一个新打开的 session [抛出“未找到当前线程的 session ”异常]。

我正在使用 Spring 3.1.1 和 Hibernate 4.1.3

有没有办法在线程中获取当前 session ?

或者有什么方法可以访问新打开的 session 到从线程调用的嵌套类?

请您参考如下方法:

当您使用 Spring 和 hibernate 时,您将使用 sessionFactory.getCurrentSession(); 获取当前 session 。如果您在交易中使用它。否则,您将收到消息异常:No Session found for current thread .

例如:

void someDBOperation() { 
   Session session = sessionFactory.getCurrentSession(); // if not in transaction, exception : No Session found for current thread 
   // some code 
} 
@Transactional  // use either annotated approach or xml approach for transaction 
void someDBOperation() { 
   Session session = sessionFactory.getCurrentSession(); // you will get session here 
   // some code 
}