grailsgrails-ormhibernate-session

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


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


Solution

  • 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:

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

    Here is the interface:

    https://github.com/grails/grails-core/blob/master/grails-core/src/main/groovy/grails/persistence/support/PersistenceContextInterceptor.java

    And Hibernate impl:

    https://github.com/grails/grails-data-mapping/blob/7cb7b7314aff3481db66a0ef3d842c6f8002ac32/grails-datastore-gorm-hibernate/src/main/groovy/org/codehaus/groovy/grails/orm/hibernate/support/HibernatePersistenceContextInterceptor.java#L37