java 在 Hibernate 中强制更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2370051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force update in Hibernate
提问by gubrutz
How can I force Hibernate to update an entity instance even if the entity is notdirty? I'm using Hibernate 3.3.2 GA, Hibernate Annotations and Hibernate EntityManager btw. I really want Hibernate to execute the generic UPDATE statement even if no property on the entity has changed.
即使实体不脏,我如何强制 Hibernate 更新实体实例?我正在使用 Hibernate 3.3.2 GA、Hibernate Annotations 和 Hibernate EntityManager btw。我真的希望 Hibernate 执行通用 UPDATE 语句,即使实体上的任何属性都没有改变。
I need this because some event listeners need to get invoked to do some additional work when the application runs for the first time.
我需要这个是因为当应用程序第一次运行时,一些事件监听器需要被调用来做一些额外的工作。
Thanks!
谢谢!
回答by gubrutz
ok - found it myself. This does the trick:
好的 - 自己找到了。这可以解决问题:
Session session = (Session)entityManager.getDelegate();
session.evict(entity);
session.update(entity);
回答by jirkamat
For transients, you can check
对于瞬态,您可以检查
if(session.contains(entity)) {
session.evict(entity);
}
session.update(entity);
回答by Lukasz Frankowski
session.evict(entity);
session.update(entity);
Good trick, but watch out for transient objects before putting this into some automation code. For transients I have then StaleStateObjectException
好技巧,但在将其放入一些自动化代码之前要注意瞬态对象。对于瞬态,我有 StaleStateObjectException
回答by Sujal Shelke
Try em.flush() which is used for EJB 3.0 entities, which also uses JPA similar to Hibernate 3.2.2 GA. If it doesn't work normally, use flush in transactions.
尝试用于 EJB 3.0 实体的 em.flush(),它也使用类似于 Hibernate 3.2.2 GA 的 JPA。如果它不能正常工作,请在事务中使用flush。

