First, I have a stateless bean which do a simple retreive, looking like this.
@Stateless
@LocalBean
public A {
@PersistenceContext
private EntityManager em;
public MyEntity retrieveMethod(){
em.createQuery(...).getSingleResult();
}
}
I have a statefull bean used to manage long conversation with a remote client, it look like this :
@Statefull
@LocalBean
@TransactionAttribute(NOT_SUPPORTED)
public class B implements BRemote {
@PersistenceContext(type = EXTENDED)
private EntityManager em;
@EJB
A a;
public void start(){
OtherEntity oe = new OtherEntity();
oe.setRelationMyEntitie(this.a.retrieveMethod());
em.persist(oe);
}
@TransactionAttribute(REQUIRED)
public void end(){
em.flush();
}
}
The problem come on executing em.persist(oe). oe has a reference to an instance of MyEntity which was loaded by another EntityManager. So em don’t know it complaining about persisting detached Entity.
I would like to know what is there is a way to avoid this problem. If there is no direct solution, what is the best pattern to adopt ?
EDIT: I don’t want to use a transaction on start() because in real application, the statefull bean is used to realize a complex entity model which need to be persist at once. I try to setup the pattern called session-per-conversation in described here http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/transactions.html#transactions-basics-apptx. So if I understand you right, the solution is to “use a transaction in start() method of bean B”, but if I do this, at the end of the method, the content is flushed to database and it’s not what I want.
Other solution I can see is to get MyEntity in the B’s EntityManager, so do a merge, or a em.find() or to delegate retrieveMethod to some DAO style class, using the em in parameter, and in bean A, do a simple delegation to the DAO, in bean B, call directly the DAO.
Any idea on what is the best approach ?
Here is the solution I used :
I hope it can help (and I hope this a not so ugly/dumb solution).