如何通过运行脚本运行时获取会话或Web应用程序上下文?

Ste*_*Kuo 3 grails

我有一个使用Grails运行的groovy脚本run-script.它从大量静态数据填充数据库.由于这个Grails/Hibernate会话问题,我必须偶尔清除会话.如果我没有,那么应用程序内存不足.因此,在运行时run-script,如何获取对会话或Web应用程序上下文的引用(GrailsWebApplicationContext)?

Ted*_*eid 5

如果您查看内部,_RunScript.groovy您将看到应用程序上下文和GrailsApplication对象被注入到脚本的绑定中.

def shell = new GroovyShell(classLoader, new Binding(ctx: appCtx, grailsApplication: grailsApp))
Run Code Online (Sandbox Code Playgroud)

有了这些,访问当前会话很容易,在您的脚本中只需向会话工厂询问当前会话,您可以清除它:

def currentSession = ctx.sessionFactory.currentSession
currentSession.clear()
Run Code Online (Sandbox Code Playgroud)