Developing portlets with Grails is great but there are still some issue to solve. Today I would talk about two problems related to GORM and Hibernate.

First: some GORM stuff works, while some others don’t and cause exceptions about the Hibernate session not being found.

For example, if we have a domain class like this:

class Car {
   Manufacturer manufacturer
   Engine engine
   Tyre tyres
   Integer seats
}

calling 

Car.get(id)

will works, but

Car.findByManufacturer()

won’t.

There are also different behaviours by calling this methods in the render phase or in the action phase.

Second: lazy load doesn’t work in .gsp views and portlet classes.

So writing

<label> ${car.manufacturer.name} </label>

cause an exception 

org.codehaus.groovy.runtime.InvokerInvocationException: org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

and, of course, the portal isn’t able to render the page.

In summary, it turns out the problem is that the OpenSessionInViewFilter doesn’t work properly in a portlet environment.

I faced this problem a few days ago and I found this solution:

first of all, I suggest to put the code that use GORM in a service class and call the service method from the portlet class. That’s because service classes can get the hibernate session with no problems and use all of the cool dynamic methods for domain classes.

Then, that service method must use domain class dynamic methods with the fetch argument set to “eager”, so the model will be fully loaded.

Your renderView closure in the portlet class will look like this:

def renderView = {
   def cars = carService.loadAllCars()
   ['cars' : cars]
  }

and here is the service method:

def loadAllCars() {
   Car.findAll([fetch:[manufacturer:"eager", engine:"eager", tyres:"eager"]])
  }

Of course setting the fetch mode to eager leads into using fewer queries than the lazy mode, because the Car model and its associations will be loaded all at once. However, if you have many associations loaded with eager fetching you will have a lots of objects loaded into memory, so be careful and pay attention while designing your service methods.