开发者

How to reinitialize lazy loaded entity?

I have an entity Person:

class Person {
  String name;
  String phone;
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  Set<Address> address开发者_JAVA百科es = new HashSet<Address>();
}

When I display persons at table I don't want to load addresses. When I open edit dialog, I want to display addresses too. But I got Lazzy loading exception (there is no active session).

How can I reinitialize Person instance to load addresses?


Call another method which will reload the person from database along with his addresses:

public Person loadPersonWithAddresses(Long personId) {
    Person p = (Person) getSession().get(Person.class, personId);
    Hibernate.initialize(p.getAddresses());
    return p;
}

or

public Person loadPersonWithAddresses(Long personId) {
    String hql = "select distinct p from Person p"
                 + " left join fetch p.addresses"
                 + " where p.d = :id";
    return (Person) getSession().createQuery(hql)
                                .setLong("id", personId)
                                .uniqueResult();
}

to do it in a single query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜