Hibernate一级缓存 - 是否同步? [英] Hibernate first level cache - does it Sync?

查看:132
本文介绍了Hibernate一级缓存 - 是否同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 会话 Hibernate 使用的第一级缓存,一旦我们从会话中检索实体,从会话而不是DB获取相同实体相同标识符的后续get调用直到会话 打开

I am aware of the fact that Session is first level cache used by Hibernate, and once we retrieve an entity from the session, the subsequent get calls for the same entity with same identifier is fetched from the session instead of DB, until the session is Open.

话虽如此,我对此有疑问hibernate如何将第一级缓存与DB同步?考虑以下场景

Having said that, I have a doubt regarding how hibernate syncs the first level cache with DB? Consider the following scenario

//Lets say I have created the session

Session s1 = sessionFactory.getSession();
User u1 = s1.get(User.class, 1); //Getting User with ID=1
//s1 is not yet closed

//Lets say I create some other session

Session s2 = sessionFactory.getSession();
User u2 = s2.get(User.class, 1); //Getting User with ID=1
u2.setName("Abc"); // Changed a field
s2.save(u2); // Saved the changes to DB
s2.close(); //Closed the 2nd session

//Now when I once again retrieve User with ID=1 from s1, will I get updated User?
User u3 = s1.get(User.class, 1);// Here as per my understanding cache is used

所以我的问题是


  • 由于提取了 u3 从第一级缓存, u3 有更新值吗?

  • 如果有人在会话开放时直接更新数据库并修改用户对象,那么会话是否与数据库同步?

  • Since u3 is fetched from 1st level cache, does u3 have updated value?
  • If some one directly updates DB and modifies User object when session is open, does the session sync with DB?

在此帖子中提前感谢您的时间和精力

Thanks in advance for your time and effort on this thread

推荐答案

不,Hibernate没有做任何事情来同步会话缓存中的实体状态与DB,除非你明确请求它。

No, Hibernate doesn't do anything to synchronize state of the entities in session cache with the DB, unless you request it explicitly.

通常它不是一个问题,因为活动工作通常发生在事务中,并且事务内的操作不应该看到其他并发事务所做的更改(但细节取决于隔离级别)。因此,在这种情况下,Hibernate的行为补充了事务隔离的典型语义。

Usually it's not a problem, because active work usually happens inside a transaction, and operations inside a transaction are not supposed to see changes made by other concurrent transactions (details depend on isolation level, though). So, behavior of Hibernate complements the typical semantics of transaction isolation in this case.

还可能存在需要明确同步实体状态以反映所做更改的情况在同一个交易中。它可能是由批量更新查询或数据库触发器的执行引起的。在这种情况下,您需要通过调用 refresh()显式请求此类同步。

There can also be situations when state of the entity need to be explicitly synchronized to reflect changes made inside the same transaction. It may be caused by bulk update queries or execution of database triggers. In this case you need to request such a synchronization explicitly by calling refresh().

这篇关于Hibernate一级缓存 - 是否同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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