Hibernate的会话线程安全吗? [英] Is Hibernate's session thread safe?

查看:202
本文介绍了Hibernate的会话线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道,Hibernate的会话是否是线程安全的。但显而易见,每个线程都会附加一个新的会话以供执行。但我的问题是,如果在一个线程中我已经更新了实体的某个值,那么它会在同一时间执行期间反映在其他线程中吗?



我的问题是当我火从两个线程顺序更新,值正确更新,但当我几乎完全启动更新,然后失败。

适用于例如。
表的当前阶段。

  ID名称标志
------- --- ------ --------
1约翰54

我试图做以下事情:

  Student student = session.load(Student.class,1); 
student.setMarks(student.getMarks()+ 1);
session.update(student);
session.close();

当我尝试在循环中运行上述代码时,如10,则表中的marks值学生已正确更新,即将值更新为64,这是正确的。



但是,当我尝试在线程环境中运行相同的代码时,结果很糟糕。

解决方案


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


即使考虑到这一点,您的行为可能仍然不是你期望,因为交易发挥作用。您将必须设置适当的事务隔离级别。请参阅配置指南 hibernate.connection.isolation 属性。


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.

解决方案

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

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的会话线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆