views:

410

answers:

4

How can I force Hibernate to update an entity instance even if the entity is not dirty? 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.

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!

+2  A: 

ok - found it myself. This does the trick:

Session session = (Session)entityManager.getDelegate();  
session.evict(entity);  
session.update(entity);
gubrutz
+1 I had heard about the trick before, but couldn't recall it.
ewernli
A: 

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.

Sujal Shelke
Flush forces Hibernate to synchronize the changes in memory with the database. But if Hibernate does not consider the entity as dirty, it won't flush anything so far I remember.
ewernli
yep - flush()ing does not help here as no changes are made
gubrutz
A: 
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

l0co
A: 

For transients, you can check

if(session.contains(entity)) {
  session.evict(entity);
}
session.update(entity);
jirkamat