java 不同线程中的休眠断言失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12705700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:54:43  来源:igfitidea点击:

Hibernate AssertionFailure in different Threads

javamultithreadinghibernateassertions

提问by bladepit

I connect to my database with one session. I have always the same session in my whole program. My Thread "1" catches primary data from the database. The user must be allowed to cancel this thread. So if the user presses the cancel button to often or to fast (this is my interpretation) the following error occures:

我通过一个会话连接到我的数据库。在我的整个程序中,我总是有相同的会话。我的线程“1”从数据库中捕获主要数据。必须允许用户取消此线程。因此,如果用户经常或快速按下取消按钮(这是我的解释),则会发生以下错误:

ERROR org.hibernate.AssertionFailure - HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session) 
org.hibernate.AssertionFailure: possible non-threadsafe access to the session

The same errors occures if i cancel my thread "2" which is running in the background after my thread "1" ist finished and the try to load another primary data set from the database.

如果在线程“1”完成后取消在后台运行的线程“2”并尝试从数据库加载另一个主数据集,则会发生相同的错误。

Is the failure that i am using the same session in my two threads?

我在我的两个线程中使用同一个会话失败了吗?

What is the right way to solve such a problem?

解决此类问题的正确方法是什么?

回答by Maciej Dragan

Each thread should obtain its own session from Hibernate session factory.

每个线程都应该从 Hibernate 会话工厂获取自己的会话。

It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.

实现者并不是线程安全的。相反,每个线程/事务都应该从 SessionFactory 获取自己的实例。

See here: Hibernate Session JavaDoc

请参阅此处:Hibernate Session JavaDoc

When you "cancel" a thread - it should do its own cleanup like transactions rollback, session close etc.

当您“取消”一个线程时 - 它应该进行自己的清理,例如事务回滚、会话关闭等。