I've read various articles on the web, but they seem rather scattered on this point. Exactly what do I need to do in my configuration and in my method to get the hibernate session. I'm trying to make some direct sql calls for stored procedures. I have a large code base that I am porting from Ruby with lots of static methods and stored procedure calls. If I need to use the sessionFactory, then how to I get access to it?
Asked
Active
Viewed 1.8k times
3 Answers
27
From a static method you can pull the sessionFactory bean from the application context:
import org.codehaus.groovy.grails.commons.ApplicationHolder as AH
...
def ctx = AH.application.mainContext
def sessionFactory = ctx.sessionFactory
def session = sessionFactory.currentSession
Burt Beckwith
- 74,294
- 5
- 136
- 152
-
Thanks Burt. I shall give this a try. – Andrew Dec 14 '09 at 15:01
-
8ApplicationHolder is now deprecated, is there an update methodology for this? – James McMahon May 30 '13 at 20:07
-
1`import grails.util.Holders` will import the non deprecated static Holder and then `Holders.grailsApplication.mainContext.sessionFactory` will give you a handle on the sessionFactory. – pendext Nov 18 '14 at 17:09
-
2Avoid `Holders`. Just because it's not deprecated doesn't mean you should use it. In fact, it has _exactly_ the same problems that `ApplicationHolder` and the others had, and should also be deprecated and removed. If all you're looking for is the current Hibernate session, `withSession` is the best option (see the answer from @michal-zmuda) – Burt Beckwith Nov 18 '14 at 17:34
23
If it's in a service or controller, you just need to declare sessionFactory
def sessionFactory
to have it injected. After that you can refer to
sessionFactory.currentSession
to use it.
Check out hibernate-filter plugin (file HibernateFilterGrailsPlugin.groovy) for how to inject a bunch of methods that use the session.
Jean Barmash
- 4,750
- 30
- 40
-
1I'm specifically looking how to get it from a domain class static method. I don't want to have to get the session from the controller and pass it into the methods. That's so 1990s' – Andrew Dec 14 '09 at 13:41
-
I tried this with Grails 2.1 and the session factory doesn't seem to be injected into the service. Burt's method above seems to still work. – Dan Polites Aug 21 '12 at 16:44
-
-
14
Michal Z m u d a
- 4,882
- 3
- 40
- 36
-
This doesn't appear to give you the full Hibernate session, instead it's a Grails session, which is missing a few methods (`createSQLQuery ` for example) – James McMahon May 21 '14 at 23:21
-
2This doesn't appear to be a comment full of truth. The session isn't a "Grails" session, it's a Hibernate session. It's easy enough to determine; replace `session.clear()` with `println session.getClass().name` and you're highly likely to see `org.hibernate.internal.SessionImpl` in the output – Burt Beckwith Nov 18 '14 at 17:32