How to I bind a Hibernate Session to a thread in Grails?

Fletch picture Fletch · Aug 24, 2010 · Viewed 10.1k times · Source

I'm writing a multi-threaded application in Grails and the additional threads need access to GORM/Hibernate. When they try to access GORM I get the error "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here".

OK fair enough, can someone guide me on the best way to set the threads up to have access? The error message almost sounds like you just need to change some config options yet I sense, it is not so simple...

Answer

Jared picture Jared · Aug 24, 2010

You need to put any GORM calls in a withTransaction closure. An example taken from a discussion of multi threading at https://fbflex.wordpress.com/2010/06/11/writing-batch-import-scripts-with-grails-gsql-and-gpars/

Single threaded

user = User.findByUsername( photo.username )

multi threaded

User.withTransaction{
user = User.findByUsername( photo.username )
}