0
votes

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?

1

1 Answers

0
votes

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