Sunday, April 1, 2012

[Java] EJB exception while trying to traverse a relationship


Excpetion - Exception Description: An attempt was made to traverse a relationship using indirection that had a null Session. This often occurs when an entity with an uninstantiated LAZY relationship is serialized and that lazy relationship is traversed after serialization. To avoid this issue, instantiate the LAZY relationship prior to serialization.


Let's suppose we have two entity beans, each representing single tables from DB. Let's suppose further that we have one table referencing another table in ONE-to-MANY relationship. For example: Publisher - Book.Entity bean for the Publisher table is going to have a collection of Book objects as it's member. Which is logical as one publisher can have several books under it's production.

Now, let's suppose we have a session bean with a method that returns a Publisher object. If we retrieve that object on the client and then try to get Book collection inside it, the exception mentioned above is going to be thrown


In the session bean method before you return the Publisher object you can make persistence provider manually traverse the relationship by calling size() method of Book collection inside.

  public Publisher getPublisherById(int id) {
try {
  Query query = em.createNamedQuery("Publisher.findById");
  query.setParameter("id", id);
  List<Publisher> pub_list = query.getResultList();
  Publisher b = pub_list .get(0);
  b.getBookCollection().size(); //manually traversing the relationship
    return b;
} catch (Exception ex) {
System.out.println(this.getClass().getName() + ".getAllBomItems:" + ex.getMessage());
return null;

Or you also can set up EAGER relationships for your persistence provider. But in the case of large database with a lot of relationships it might reduce the performance greatly.

1 comment:

  1. Hallo
    I have same error with your article but i have entity class with use Hashset.
    How can i solve my bugs ?

    Sorry my english's language is not well.