我使用
得到一个实体“A”getHibernateTemplate().get(A.class, 100)
来自数据库。假设这个实体“A”在数据库中有一个属性“值”200。
现在,在我的 Java 代码中,我更改了该实体的属性。可以说,我将“value”属性更改为“500”,然后将其添加到某个列表中。
现在,如果我再次对同一个实体执行 getHibernateTemplate().get(A.class, 100) 操作,我将获得更新后的实体(值为 500)。如何强制 hibernate 从数据库中获取实体,而不是代码中更新的实体?
这就是所谓的“一级缓存”吗?
最佳答案
您的假设(关于一级缓存)是正确的。例如这里所述:Interface Session :
The main runtime interface between a Java application and Hibernate. This is the central API class abstracting the notion of a persistence service.
或者这里第 2 章:架构; 2.1. Overview
摘录: session (org.hibernate.Session)
A single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps a JDBC connection and is a factory for Transaction. Session holds a mandatory first-level cache of persistent objects that are used when navigating the object graph or looking up objects by identifier.
此外,您还可以看到我们可以使用的方法来从 session 中删除对象:
驱逐(对象对象): 从 session 缓存中删除此实例。
刷新(对象对象): 从底层数据库重新读取给定实例的状态。
- 清除(): 完全清除 session 。
还有更多。在这种情况下,Evict
应该可以工作。我们必须获取当前实例(“A”)并显式地从 session 中Evict
它。
如果我们已经加载了一些/更多的东西,并且我们不知道要Evict()
做什么,我们只需要获取新数据即可。然后我们可以调用Clear()
来完全重置 session 并重新开始。
这有点激进,因为 session 中的任何对象都不会在 session Flush()
上更新/插入...但这可能是我们在这种情况下想要的 (经常用于测试...加载、清除...更改和刷新)
关于java - Hibernate 返回 session 中的值,而不是从数据库中返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867301/