2

Beacause of the issues mentioned in : Why not to use Spring's OpenEntityManagerInViewFilter

and

http://heapdump.wordpress.com/2010/04/04/should-i-use-open-session-in-view/

I'd like to use an alternative for Springs OpenentityManagerInViewFilter. This is definitely a performance issue. If I disable the OpenentityManagerInViewFilter I ocassionally get the error:

LazyInitializationException:42 - failed to lazily initialize a collection 
Community
  • 1
  • 1
avijendr
  • 3,958
  • 2
  • 31
  • 46

1 Answers1

2

One alternative to the filter is to access all of elements in a collection that is lazy loaded before sending them via the request to the view. However, at this point you should question whether these attributes need to be eagerly fetched.

Here is some psuedo code to demonstrate.

   //Inside controller
   Department dept = dao.findDepartment(id);

   //This will load the entities, avoiding the exception.
   for(Employee e: dept.getEmployees()){ //Assume employees are lazy loaded
     e.getName();
   }

   request.setAttribute("department", dept); //In Spring this could be the model
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Thanks Kevin. But this won't be a apt solution. Considering our application being huge, we can't go ahead and change this everywhere in the code. A bit more subtle approach would be to use some sort of DTO or something similar. But we are leaving this as it is for the moment. Eagerly fetching wouldn't either be a good solution anyways. – avijendr Apr 29 '13 at 14:54
  • 2
    @avijendr Checkout the book Pro JPA2 it has a few methods for solving this problem, I believe in the EntityManager chapter. I don't have it available at the moment. – Kevin Bowersox Apr 29 '13 at 15:53