9

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?

Andrew
  • 2,257
  • 4
  • 26
  • 40

3 Answers3

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
  • 8
    ApplicationHolder 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
  • 2
    Avoid `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
14

You can use withSession

Book.withSession { session ->
    session.clear()
}

More info

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
  • 2
    This 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