Grails集成测试和sessionFactory.currentSession

Grails集成测试和sessionFactory.currentSession,grails,Grails,由REST调用触发的从远程服务器加载数据的进程。集成测试失败,原因是: java.lang.NullPointerException: Cannot get property 'currentSession' on null object 加载了大量数据,因此每加载几百条记录,调用就会刷新一次: protected cleanUpGorm() { def session = sessionFactory.currentSession session.flush() se

由REST调用触发的从远程服务器加载数据的进程。集成测试失败,原因是:

java.lang.NullPointerException: Cannot get property 'currentSession' on null object
加载了大量数据,因此每加载几百条记录,调用就会刷新一次:

protected cleanUpGorm() {
    def session = sessionFactory.currentSession
    session.flush()
    session.clear()
}

如上所述,未加载会话工厂。这是一个“helper groovy类”——既不是服务也不是控制器。我现在必须按照GrailsApplication传递sessionFactory吗?

问题在于将“sessionFactory”bean注入到常规groovy类中。 应使用以下代码对其进行访问:

ApplicationContext context = (ApplicationContext) ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
SessionFactory sessionFactory = context.getBean('sessionFactory')
Session currentSession = sessionFactory.getCurrentSession()
获取当前会话的另一种技术可以使用grails实用程序类:

Session session = RequestContextHolder.currentRequestAttributes().getSession()


不幸的是,您正在谈论通过grails实用程序类检索会话的问题
WebUtils.retrieveGrailsWebRequest().session
不是org.hibernate.session的亲戚
GrailsHttpSession
是来自不同类族的继承器。因此,使用
def session=WebUtils.retrieveGrailsWebRequest().session
将不允许执行诸如
session.createSQLQuery(…)
之类的请求。我还在挠头,不知道在集成测试中真正模拟sessionFactory是否可行。以上所有建议对我都不起作用
Session session = WebUtils.retrieveGrailsWebRequest().session