如何在没有 LazyInitializationException 的情况下接收实体?

How to receive the entity without LazyInitializationException?

我有两个实体:

  A
  id bigint auto_inctement
  b_id bigint

  B
  id bigint
  date timestamp

和代码:

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();
    }
}

如何正确接收b.getDate()? (没有懒惰="eager")

当您试图在会话关闭后获取数据时,您可以尝试使用:

Hibernate.initialize(b.getDate())

这里有更多详细信息http://docs.jboss.org/hibernate/core/3.5/reference/en/html/performance.html#performance-fetching-initialization