Grails集成测试和sessionFactory.currentSession

时间:2014-09-06 06:58:06

标签: grails

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

java.lang.NullPointerException: Cannot get property 'currentSession' on null object

加载大量数据,因此每隔几百条记录就会调用flush:

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

如上所述,未加载会话工厂。这是一个帮助groovy类' - 无论是服务还是控制器。我现在必须按照GrailsApplication传递sessionFactory吗?

1 个答案:

答案 0 :(得分:0)

问题在于注射" 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()

Session session = WebUtils.retrieveGrailsWebRequest().session