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.