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

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

问题描述

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

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.

例如.表的当前阶段.

  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();

当我尝试在循环中运行上述代码时说 10,然后表student"中marks"的值被正确更新,即该值被更新为正确的 64.

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.

推荐答案

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

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

即使考虑到这一点,您的行为仍可能不是您所期望的,因为交易会起作用.您必须设置适当的事务隔离级别.请参阅配置指南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 的会话线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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