In Grails how do I access the hibernate session inside of a domain class static method?

限于喜欢 提交于 2019-12-03 07:38:00

问题


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?


回答1:


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



回答2:


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.




回答3:


You can use withSession

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

More info



来源:https://stackoverflow.com/questions/1898684/in-grails-how-do-i-access-the-hibernate-session-inside-of-a-domain-class-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!