Tuesday 19 November 2013

Hibernate Associations and Discards/Evicts

Right, so your sitting at work thinking how life would be without the Hibernate ORM...and you would go.... very frustrating indeed. Most of the time, you'd be busy mapping your SQL to your Java instances and vice versa.

But then again, Hibernate does come with its own set of headaches. Here is something I learnt recently.. that hibernate will not tell you.

You have your domain instance and your hibernate session and for whatever reason, you decide to evict it (also known as discard in the Grails world). For single entities, you see that this works just fine...but most system work with a graph of entities....not just one.

Suppose you have domain class A that has one or more class B objects. Should you decide to evict on class A, and you find class B is dirty (meaning some attribute has changed there), you will see that your discard just gets ignored. After all, if class B is updated and class A relies on it, the relationship between A and B needs to get refreshed and as a result, Hibernate just cannot ignore not persisting A.

So what is the solution you ask....you need to evict EVERY B as well as A. Essentially, this tells hibernate that nothing is dirty and now finally, A will not get persisted.

1 comment: