When trying to optimize transactions on my java ee 6 project using hibernate, I tried to do as I did with Eclipselink and have transactions turned off for read-only queries, like follows:
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public User fetchUser(Integer id){
User u = em.find(User.class, id);
u.getRoleList().size();
return u;
}
In hibernate, this throws and exception when trying to read the user roles, claiming the session was closed already. Does hibernate lazy loading really require a full scaled EJB transaction just for reading data?
In short, yes.
Having a transaction is a good idea anyway because
em.findand the one for the lazy loading) see the database in the same state: the second read doesn’t see something committed right after the first one, for example.