Foo 看起来有这个:
@ManyToMany
private Set<User> favouritedBy;
而用户有这个:
@ManyToMany(mappedBy = "favouritedBy")
private Set<Foo> favourites = new HashSet<Foo>();
public Set<Foo> getFavourites() {
return favourite;
}
并且 fooService 有这个,在会话打开时通过事务方法访问延迟加载的集合:
@Transactional(readOnly = true)
public Set<Foo> getFavourites(User user) {
user = dao.get(User.class, user.getId()); //the dao gets a session
Set<Foo> favourites = user.getFavourites();//but the session is not here and the exception is thrown?
return favourties;
}
编辑 这修复了它,而不使用标准:
Set<Foo> favourites = new HashSet<Foo>(user.getFavourites());
这用标准修复它
Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(Foo.class);
crit.setFetchMode("favourites", FetchMode.JOIN);
crit.add(Property.forName("id").eq(id));
return (Foo) crit.uniqueResult();