如何实施“更新”在Hibernate JPA2中 [英] HowTo implement "update" in Hibernate JPA2
问题描述
@Override
public void update(final BS bs){
BS fullBs = em.find(BS.class,bs.getId());
BS合并= this.em.merge(fullBs);
this.em.flush();
谢谢
ER
hibernate中的更新使用脏检查而不是显式更新调用来实现。例如,在上面的方法中,如果 find()您的BS实体,然后修改一个属性,然后调用 flush()
您将看到正在生成的SQL更新。没有修改 flush()
会决定没有任何事情可做。
示例
@Override
public void update(final BS bs){
BS fullBs = em.find(BS.class,bs.getId ());
fullBs.setMyProperty(hello);
this.em.flush();
$ / code>
当您执行 find()
该实体由JPA提供程序(本例中为hibernate)加载,并且hibernate将为您提供该实体,并且它在实体状态的内部记录中保存实体状态的内部记录,并保存对实体的引用返回。
然后,当
请注意 flush()
不是事务提交。它只是说,请将会话中对数据库所做的任何更改持久化,这将涉及插入/更新/删除语句。
()
对于一个简单的更新不是必需的。
另外你通常不会调用 flush() / code>明确。让休眠做到这一点通常会更好。 Hibernate会在需要时刷新会话,这通常会在事务提交上进行,因此提交会为您执行刷新。
Could someone provide a simple example that demonstrates how to implement a simple "update" method? This one does not update
@Override
public void update(final BS bs) {
BS fullBs = em.find(BS.class, bs.getId());
BS merged = this.em.merge(fullBs);
this.em.flush();
}
Thanks
ER
Updates in hibernate are implemented using dirty checking rather than explicit update calls. For example in the method above if you find()
your BS entity and then modify a property and then call flush()
you will see an SQL update being generated. Without the modification flush()
will decide there is nothing to do.
Example
@Override
public void update(final BS bs) {
BS fullBs = em.find(BS.class, bs.getId());
fullBs.setMyProperty("hello");
this.em.flush();
}
When you do the find()
the entity is loaded by the JPA provider (hibernate in this case) and hibernate will give you the entity AND it keeps an internal record of the entity state at the point it was loaded PLUS it hold a reference to the entity it returned.
Then when flush()
is called hibernate dirty checks every entity in its cache (called the first-level cache or session cache). The dirty checks consists of checking every property of the entity you got with the internal state record. If there are any differences the entity is "dirty" and an SQL update will be generated.
Note that flush()
is not a transactional commit. It simply says, "please persist any changes made in the session to the database now" which will involve insert/update/delete statements.
The merge()
is not required for a simple update.
Also you don't generally call flush()
explicitly. It's normally better to let hibernate do that. Hibernate will flush the session when it needs to, which will usually be on a transaction commit, so the commit will do the flush for you.
这篇关于如何实施“更新”在Hibernate JPA2中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!