Foo looks has this in it :
@ManyToMany
private Set<User> favouritedBy;
while user has this:
@ManyToMany(mappedBy = "favouritedBy")
private Set<Foo> favourites = new HashSet<Foo>();
public Set<Foo> getFavourites() {
return favourite;
}
And fooService has this, with the lazyloaded collection being accessed while session is opened, via the tranactional method :
@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;
}
EDIT This fixes it, without using criteria :
Set<Foo> favourites = new HashSet<Foo>(user.getFavourites());
and this fixes it with criteria
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();
transactionManager
set in spring context andtx:annotation-driven
defined? – Meristic