Thursday, October 11, 2012


Hibernate Collections implementations

So your Hibernate entity has a reference to collection of other entities mapped using Set interface (or for that matter any other collection interface). You load an entity from database and in your debugger inspect the type of the collection Hibernate is using ( assuming it is configured as eagerly loaded. Lazy loading is quite another story for another day). You expect it to be usual java implementation HashSet but you see something as PersistentSet. You are bewildered and scratching your head jump to the Hibernate manuals or different forums. Go no further ! Here is what is happening under the hood !

Whenever hibernate is used for querying an object, an entity is returned which is managed by Hibernate as long as the session in which it was queried is open. Behind the scenes Hibernate queries the database and builds the entity object. The entity might contain associations in form of Single object association or Collections. In case of collections, hibernate creates its own implementation of collection. For e.g., for a List type it creates a wrapper list Persistent List. All the java collections like Set, HashMap etc. have their corresponding implementaions in Hibernate.
The base class for all these hibernate implementations is AbstractPersistentCollection as you can see below in the type hierarchy.
You will never have to directly deal with these Hibernate classes however it's good to understand the inner working of collection mapping.


All these implementations are wrapper over the original collection in the entity (decorator pattern you see !). There are many  things for which Hibernate uses these implementations classes. One of the things Hibernate uses these implementations is to mark the collections as dirty. Whenever you add/remove an object in these collections, it marks the collection dirty and Hibernate can queue the update query later when it inspects the collection. AbstractPersistentCollection maintains a Boolean variable “dirty” to indicate this and it is updated whenever there is any change to the collection via its interface.

No comments:

Post a Comment