11

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!

gubrutz
  • 249
  • 1
  • 2
  • 6

4 Answers4

13

ok - found it myself. This does the trick:

Session session = (Session)entityManager.getDelegate();  
session.evict(entity);  
session.update(entity);
gubrutz
  • 249
  • 1
  • 2
  • 6
  • +1 I had heard about the trick before, but couldn't recall it. – ewernli Mar 03 '10 at 10:29
  • Neat trick but I just tried it and it is worth while to point out that if you are also interested in having this commit "entity.childEntity" it will not--it breaks the dependency tree. – Bill K Aug 19 '11 at 16:01
4

For transients, you can check

if(session.contains(entity)) {
  session.evict(entity);
}
session.update(entity);
jirkamat
  • 1,776
  • 2
  • 15
  • 17
2
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

Lukasz Frankowski
  • 2,955
  • 1
  • 31
  • 32
0

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.

  • 1
    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 Mar 03 '10 at 10:33
  • yep - flush()ing does not help here as no changes are made – gubrutz Mar 03 '10 at 10:37