gpt4 book ai didi

spring - 如何在线程中访问 hibernate session ?

转载 作者:行者123 更新时间:2023-12-03 11:27:31 47 4
gpt4 key购买 nike

由于 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
}

关于spring - 如何在线程中访问 hibernate session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13061746/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com