强制 Hibernate 查询访问数据库
我已将一个实体加载到我的交易中并更改了该实体的属性。该交易尚未提交。现在我想获取更改后的属性的原始值。
我尝试过使用 HQL 查询,例如 select p.property from Person p where p.id = 1
以及事务中加载的实体的 ID。
我在执行查询之前设置了 query.setHint("org.hibernate.cacheMode", CacheMode.IGNORE);
。但没有成功。 Hibernate 返回当前事务中设置的值,而不是数据库中的值。
有什么办法解决这个问题吗?
I have loaded an entity into my transaction and have changed a property of that entity. The transaction is not yet commited. Now I would like to get the original value of the changed property.
I've tried with a HQL query like select p.property from Person p where p.id = 1
with the ID of the entity loaded in the transaction.
I've set query.setHint("org.hibernate.cacheMode", CacheMode.IGNORE);
before executing the query. But no success. Hibernate returns the value as set in the current transaction, not the one from the database.
Is there any way around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简而言之:自己跟踪旧值。
Hibernate 将给定数据库标识符的实体的唯一版本加载到会话(第一级缓存)中。这行不通。
此提示用于影响查询缓存(依赖于二级缓存),这不会影响您当前的“问题”。
使用
session.refresh()
强制重新加载实体(并且您将丢失更改)In short: track the old value yourself.
Hibernate loads a unique version of an entity into the session (the first level cache) for a given database identifier. This won't work.
This hint is used to affect the query cache (that rely on the second-level-cache), this won't affect your current "issue".
Either
session.refresh()
to force a reload of your entity (and you'll loose the changes)StatelessSession 对我有用。
The StatelessSession worked for me.
这可能有帮助:
(来自http://docs.jboss.org/hibernate/stable/core/reference/en/html/performance.html,第 20.4.2 节)。
但是,它是否打算在其他进程更新数据库时使用,应谨慎使用。
你的情况有所不同。由于此方法发生在任何事务之外,因此您应该确保它不会与您的设计冲突。也许您可以重构您的调用流程以避免这种行为,并从另一个源或在缓存中的修改发生之前检索该字段......
This may help:
(From http://docs.jboss.org/hibernate/stable/core/reference/en/html/performance.html, section 20.4.2).
However, is it intended to use when other process is updating the DB, and should be used with care.
Your case is different. As this method occurs outside any transaction, you should be sure it does not conflict with your design. Maybe you can refactor your call flow to avoid that behavior, and retrieve the field from another source or before the modification in the cache takes place...
执行此操作的唯一方法是在当前事务之外运行查询。
The only way to do this would be to run the query outside of the current transaction.