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.
精彩评论