Search code examples
hibernatelazy-initialization

How to receive the entity without LazyInitializationException?


I have two Entities:

  A
  id bigint auto_inctement
  b_id bigint

  B
  id bigint
  date timestamp

and code:

public void test2() {
    B b = getBByA(3l);
    System.out.println(b.getDate()); // <--- lazy initialization exception
}

public Revision getBByA(long a_id) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        A a = (A) session.get(A.class, a_id);

        return a.getB();
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw e;
    } finally {
        session.close();
    }
}

How it is correctly to receive the b.getDate()? (without lazy="eager")


Solution

  • As you are trying to fetch data after session is closed, you may try to use:

    Hibernate.initialize(b.getDate())
    

    here are some more details http://docs.jboss.org/hibernate/core/3.5/reference/en/html/performance.html#performance-fetching-initialization