开发者

Hibernate lazy loading requires EJB transaction?

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开发者_C百科 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

  • it guarantees that both requests (the one for em.find and 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.
  • it makes the session live for the time of the transaction, which optimizes the loading since it may reuse the objects cached in the session, avoid loading the same entity several times, etc.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜