I'm hitting 'org.hibernate.SessionException: collections cannot be fetched by a stateless session'

Solution Verified - Updated -

Environment

  • Java Persistence API (JPA)
  • Hibernate

Issue

  • The following error is raised when I enable lazy loading on a particular collection, the application code used to work before the change

    org.hibernate.SessionException: collections cannot be fetched by a stateless session
    

Resolution

The use of lazy loading in conjunction with stateless session are not compatible.  You either need to do one of two things

  1. Use a stateful Hibernate session
  2. Disable lazy loading for the involved assocation

Root Cause

The stateless hibernate session doesn't keep any first level cache nor acts as a persistence context. It is not able to handle loading on-demand.

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

Comments