Hibernate的会话线程安全吗?
我需要知道 Hibernate 的会话是否是线程安全的。但显然,每个线程都会附加一个新会话来执行。但我的问题是,如果在一个线程中我更新了实体的某些值,那么在同一时间执行期间这会反映在其他线程中吗?
我的问题是,当我依次从两个线程触发更新时,该值会正确更新,但是当我几乎完全触发更新时,它会失败。
例如。 表的当前阶段。
ID NAME MARKS
------- --------- --------
1 John 54
我正在尝试执行以下操作:
Student student = session.load(Student.class, 1);
student.setMarks(student.getMarks() + 1);
session.update(student);
session.close();
当我尝试在循环(例如 10)中运行上述代码时,表“student”中“marks”的值会正确更新,即该值会更新为正确的 64。
但是当我尝试在线程环境中运行相同的代码时,它会给出不好的结果。
I need to know, whether the Hibernate's session is thread safe or not. But obvious a new session is attached to every thread for execution. But my question is if in one thread I have updated some value of an entity, so will that be reflected in other thread during same time execution?
My problem is when I fire update from two threads sequentially, the value is updated properly but when I fire the update almost altogether then it fails.
for eg.
current stage of table.
ID NAME MARKS
------- --------- --------
1 John 54
I am trying to do follwing :
Student student = session.load(Student.class, 1);
student.setMarks(student.getMarks() + 1);
session.update(student);
session.close();
When I try to run the above code in loop say 10, then value of "marks" in table "student" is properly updated i.e. the value gets updated to 64 which is proper.
But when I try to run the same code in threaded environment, it gives bad results.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
即使考虑到这一点,您的行为可能仍然不是您所期望的,因为交易发挥了作用。您必须设置适当的事务隔离级别。请参阅配置指南,
hibernate.connection.isolation
属性。Even with this in mind, your behaviour might still not be what you expect, because transactions come into play. You will have to set a proper transaction isolation level. See the configuration guide,
hibernate.connection.isolation
property.Hibernate 会话和线程不混合。
您不应该同时使用来自多个线程的会话,我建议您仅使用来自单个线程的会话。数据库会话实现甚至不需要是广告安全的。
您还必须考虑当您开始在多个线程中执行操作时事务会发生什么情况。事务与当前线程绑定。这很快就会变得令人震惊,并且您进入了实施者尚未测试其产品的领域。
最终,生命太短暂,不能迷失在沼泽中。
Hibernate session and threads do not mix.
You should not use a session from multiple threads at once, and I recommend you only use a session from a single thread. DB session implementations are not even required to be theadsafe.
You also must consider what happens to the transactions when you start doing things in multiple threads. Transactions are tied to the current thread. This becomes quickly mindblowing and you enter areas where the implementers have not tested their products.
In the end life is too short to get lost in that swamp.
这取决于您如何创建会话。
在hibernate中可以通过两种方式创建Session。
It depends on how you are creating a session.
Session can be created in two ways in hibernate.
Hibernate 会话不是线程安全的。使用 TheadLocal 类为每个线程创建会话:-
在您的方法中,为每个线程获取会话:-
Hibernate sessions are not thread safe. Use TheadLocal class to create sessions for each thread:-
In your method get session for each thread as:-