1

I have @Stateless ejb's deployed in my web application. This web application is deployed in glassfish V3.0.1

My domain model is made of two classes : Master and Slave, the master being associated to many slaves.

I have a jsf view MyView, calling the method displaySlaves on my ejb MyEjb

When in the method displaySlaves of my stateless ejb MyEjb i do this, all works fine :

    Master master = getEntityManager().find(Master.class, 0L);
    Set<Slave> slaves = master.getSlaves();
    System.out.println("Master : " + master + " and slaves "+ slaves.size());

But if i try from my view MyView to get a reference on master (MyEjb returns only the master instance, but doesn't call master.getSlaves()) and then in MyView i call getSlaves() on the returned master instance i get :

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of Slave : no session or session closed.

Obviously when the thread exits of the ejb, the session is closed. That is the reason of the error.

But when i use eclipseLink instead of hibernate, all is fine, i have no session problem. EclipseLink doesn't close the transaction when exiting the ejb. That is much more easy to code the view browsing the returned model instance, than getting all associated objects of the model instance in the ejb method.

Does anybody has an explanation or a workaround to make it work with Hibernate ? My previous problem is just an illustration, and in real I have a legacy application with many many mapped classes , and the refactoring of annotations required to make it work with eclipseLink seems an huge task.

Any help appreciated.

Components :

  • Glassfish 3.0.1
  • windows 7 64 bits JDK Sun 1.6.0.24
  • Hibernate 3.5.6-Final
  • tiredOldDevelopper v1 final - fading.
jan groth
  • 12,429
  • 5
  • 34
  • 51
oliviert
  • 11
  • 2

1 Answers1

1

What you are describing is bugging developers since years. Rumors say that Gavin King (creator of Hibernate) developed JBoss Seam mainly to provide a clean solution for lazy loading in views ;-)

Couple of options:

  • disable lazy loading in your JPA metadata (FetchType.EAGER)
  • read about the infamous "open session in view pattern", but don't use it
  • if you need lazy loading in your views, consider putting an extended persistence context in the CDI conversation scope (that's what I would prefer)
Community
  • 1
  • 1
jan groth
  • 12,429
  • 5
  • 34
  • 51
  • Thank you for your answer. After many searches, it seems indeed that nothing magic is just standing out of the box. Ejbs suck anyway, each time I have to work with, I fall on a limitation that would not have existed if the project was done with a little conception and help from something like Weld or Spring (sorry for the troll on ejbs but it is true). It is better to do something with our own hands than relying on something too closed. – oliviert Jan 05 '12 at 10:50