0

I am using jQuery for UI, Struts2 as Action, JPA for Data Access Layer.

The issue I am facing is that I am getting LazyInitializationException when I try to retrieve values from the database. I get the stacktrace below:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.singpost.ctf.core.persistence.CtfTxn.ctfTxnAttribs, no session or session was closed

When by default Fetch="LAZY", the code is working fine. But when I change the Fetch type to EAGER, I don't know what I have to do further. I am stuck in the middle.

Esh
  • 836
  • 5
  • 16
  • 43
  • 1
    possible duplicate of [JPA LazyInitializationException?](http://stackoverflow.com/questions/11790289/jpa-lazyinitializationexception) – ecatmur Nov 06 '12 at 15:13

2 Answers2

0

As the error message states, the hibernate session has already been closed when you try to access the collection. The solution is to either make sure the session is still open (if you're using JTA, the session will be closed when the transaction commits), or to not use lazy loading (as you've discovered).

Zareth
  • 477
  • 2
  • 5
-1

I don't know what I have to do further.

I expand on Zareth's answer because this is a common problem.

One thing to do is understand that, when fetch=FetchType.LAZY is declared on the mapping of the ctfTxnAttribs, then JPA will load a collection of proxy objects: each object appears to be a ctfTxnAttrib, but is only a proxy.

This may appear to all be working fine, until your web page or bean attempts to access an object in that collection. Then you get the lazyInitializationException because the persistence provider finds only proxies.

As Zareth pointed out, you need an open persistence session, to populate the collection of proxies with real instances of ctfTxnAttrib.

There are various ways to implement this, and here's a very good article about the topic, including the design pattern, Open Session In View:

http://www.javacodegeeks.com/2012/07/four-solutions-to-lazyinitializationexc_05.html

J Slick
  • 929
  • 11
  • 17