views:

41

answers:

2

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?

+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
@Daniel, is sessionFactory.getCurrentSession thread safe? Im wondering since he is trying to access it from a static utility method.
hvgotcodes
@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
+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