Search code examples
grailsgrails-orm

HibernateException: No Session found for current thread when GORM query moved into another domain class


In grails, I have a Domain class and can be queried in BootStap.groovy

def xref = AppXref.find{user_nm == 'john'}

However, once I moved the code into a method of another Domain class I will have the following error.

Servlet.service() for servlet [default] in context with path [/myapp] threw exception
Message: Could not obtain current Hibernate Session; nested exception is org.hibernate.HibernateException: No Session found for current thread

Here is my hibernate config in Config.groovy

hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
//    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
    cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
    singleSession = true // configure OSIV singleSession mode
    flush.mode = 'manual' // OSIV session flush mode outside of transactional context
}

I changed cache.use_query_cache to true. But it made no difference.


Solution

  • domain class methods are NOT transactional, so you have to make sure, that they are invoked in a TX-context: either put them in a service, or use .withTransaction{}