Monday, November 11, 2013

GORM & Lazy Load

There is a tricky thing going on using Domain Classes with collection and Lazy loading. Immagine this situation:

It is quite normal to have the collection represented by a proxy in order to perform lazy loading, in fact in those cases the collection items in reallyDummies are represented in memory with objects similar to this one:

ReallyDummy_$$_javassist_7

at least till first time you access to the collection. If that happen an handler instance of GroovyAwareJavassistLazyInitializer take cares to load the collection from the datasource and associate it to the right object.

The tricky thing is that is not so rare to take decisions accordingly to the class we hare handling, but what happens when you get a proxy instead of the real object?
piece of code like this :

reallyDummies.each{ it ->
  if (obj instanceof BasicDummy){ ... }
}

is almost useless! this because you cannot predict if the object that belongs to a collection o a property explicitly loaded in lazy manner is already in the session and if it will be loaded properly only looking at its base class.

To solve the problem you have two choice:
  1. use the method obj.instanceOf() provided by GormInstanceApi that take care to unproxy the object if needed.
  2. use GrailsHibernateUtil.unwrapIfProxy(obj) if you use only hibernate as datasource.

Remember that GORM Domain Classes are really powerful and originally they were built on top of Hibernate functionality and capabilities.
Form Grails 2.X Hibernate as become a plugin and can be replaced, so GORM can now work with many NoSql datasources!


No comments:

Post a Comment