Grails集成测试和sessionFactory

Grails集成测试和sessionFactory

本文介绍了Grails集成测试和sessionFactory.currentSession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  java.lang.NullPointerException:无法在空对象上获取属性'currentSession'

加载大量数据,所以调用每载入几百条记录:

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

如上所述,会话工厂未加载。这是一个'助手时髦类' - 既不是服务也不是控制器。我现在必须按照GrailsApplication传递sessionFactory吗?

解决方案

问题是将sessionFactorybean注入到常规的groovy类中。
它应该可以使用下面的代码访问:

pre $ ApplicationContext context =(ApplicationContext)ServletContextHolder.getServletContext()。getAttribute (GrailsApplicationAttributes.APPLICATION_CONTEXT);
SessionFactory sessionFactory = context.getBean('sessionFactory')
Session currentSession = sessionFactory.getCurrentSession()

另一种获取当前会话的技术可以使用grails工具类:

 会话会话= RequestContextHolder.currentRequestAttributes ().getSession()

  Session session = WebUtils.retrieveGrailsWebRequest()。session 


Process that loads data from a remote server, triggered by a REST call. The integration test fails with:

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

The loads a lot of data, so calls flush every few hundred records loaded:

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

As noted the session factory is not loaded. This is a 'helper groovy class' - neither service or controller. Do I have to now pass sessionFactory as per GrailsApplication?

解决方案

The problem is with injection "sessionFactory" bean into regular groovy class.It should be accessible using the following code:

ApplicationContext context = (ApplicationContext) ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
SessionFactory sessionFactory = context.getBean('sessionFactory')
Session currentSession = sessionFactory.getCurrentSession()

Another technique for fetching the current session can be using grails utility class:

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

or

Session session = WebUtils.retrieveGrailsWebRequest().session

这篇关于Grails集成测试和sessionFactory.currentSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:12