views:

179

answers:

2

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...

+1  A: 

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 )
}
Jared
+1  A: 

There is a bean in Grails applications called “persistenceInterceptor” that can be used for this.

See this example from the JMS plugin on how to use it:

http://github.com/gpc/grails-jms/blob/master/src/groovy/grails/plugin/jms/listener/adapter/PersistenceContextAwareListenerAdapter.groovy#L21

Here is the interface:

http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/support/PersistenceContextInterceptor.java#L29

And Hibernate impl:

http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/orm/hibernate/support/HibernatePersistenceContextInterceptor.java#L32

Luke Daley
I'd like to give you twenty points for this answer if I could. This just fixed my problem after I've been banging my head on the wall for hours.
Milan Ramaiya