Tuesday, May 4, 2010

Hibernate exception in Grails-1.2.1 when working with services and quartz cron jobs

Happens when we instantiate a service using new operator.

grails ERROR [PatchedDefaultFlushEventListener][] Could not synchronize database state with sessionorg.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

http://jira.codehaus.org/browse/GRAILSPLUGINS-1776?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel#issue-tabs : syas that it happens when making changes to unsaved domain object in a background thread

http://jira.codehaus.org/browse/GRAILSPLUGINS-1807
http://jira.codehaus.org/browse/GRAILSPLUGINS-1808? page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel#issue-tabs

What worked for me:
Within the service' method being called inject hibernate SessionFactory as follows

http://stackoverflow.com/questions/1898684/in-grails-how-do-i-access-the-hibernate-session-inside-of-a-domain-class-static-m

import org.codehaus.groovy.grails.commons.ApplicationHolder as AH
class BlahService{
 blahMethod(){
  def ctx = AH.application.mainContext
  def sessionFactory = ctx.sessionFactory
  def session = sessionFactory.currentSession

  blah blah blah code containing GORM usage

  session.flush()
  session.clear() //optional
 }
}

No comments:

Post a Comment