I got a singleton service and inside its only method I need to obtain a reference to the hibernate session bound to the current request. What is the quickest way of doing that?
views:
41answers:
2
+2
A:
We do it the following way:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class YourService {
SessionFactory sessionFactory // set by Dependency Injection
public void yourMethod() {
Session session = sessionFactory.getCurrentSession();
// do something with session
}
}
When your service is in the grails-app/services directory and ends wirh "Service", the sessionFactory is injected by grails.
Daniel Engmann
2010-08-11 12:36:12
@Daniel, is sessionFactory.getCurrentSession thread safe? Im wondering since he is trying to access it from a static utility method.
hvgotcodes
2010-08-11 14:10:03
@hvgotcodes, take look at this - http://www.redhat.com/docs/en-US/JBoss_Hibernate/3.2.4.sp01.cp03/api/hibernate-core/org/hibernate/context/CurrentSessionContext.html
Olexandr
2010-08-11 14:41:37
+4
A:
Or just
def someServiceMethod {
SomeDomainObjectClass.withSession { session ->
.....
}
}
Domain objects are classes defined in grails-app/domain directory.
session
variable will obtain current Hibernate Session reference inside withSession
closure.
archer
2010-08-11 16:05:16