Generally, an Entity bean is maintained in an "attached" state as long as the transaction is active. Since most implicit transactions begin and end with an the EJB method call your entity becomes "detached" once the invoked EJB method reaches its end. This means you should do all your lazy loading when you fetch the object.
For example: | @Stateless | public class MyDAO { | @PersistenceContext | EntityManager em; | | // transaction begins | public List<Entity> fetchEntity(Long id) { | List<Entity> results = em.createQuery("select e from Entity where e.id = :id").setParameter("id", 1L).getResultList(); | | // lazy load something from retrieved entity | | return results; | } | // transaction ends | } | You should be able to stretch things out if your willing to do your own transaction management - however I'm very fuzzy on this issue so i'm probably not the best person to ask. If your using a Stateful Session Bean, you can go with an Extended Persistence Context (@PersistenceContext(type = PersistenceContextType.EXTENDED)), which provides an session scoped EntityManager allowing you to maintain attached entities across a session - but again, this depends on the transaction in play, and the entity will become detached when the transaction ends. Another consideration is Serialization. If your in a clustered environment, you'll find that the serialization/de-serialization of entities across servers (called passivation & activation) can also detatch your entities. So even if you have a Stateful Session Bean and an extended persistence context - you can still get the LazyInitializationExeption between requests. Some newer frameworks can help you out here as well. Seam provides a "Conversation Scoped EntityManager" which can span multiple request/response cyles (so you rarely have a detached entity). Seam also handles clustering and the serialization/serialization of entities in your session and conversation scopes - so you don't have to worry about serialization detaching your entities either. Spring provides an OpenEntityManagerInView filter which provides similar functionality - although I don't believe it works between requests. I believe Struts2 has a plug-in to provide similar functionality. I hope all this helps, and that i didn't screw things up too badly (someone please correct me if i did :P). View the original post : http://www.jboss.org/index.html?module=bb&op=viewtopic&p=4229820#4229820 Reply to the post : http://www.jboss.org/index.html?module=bb&op=posting&mode=reply&p=4229820 _______________________________________________ jboss-user mailing list jboss-user@lists.jboss.org https://lists.jboss.org/mailman/listinfo/jboss-user