I have Stateless Session Bean with Container-Managed Transactions. I want to return unmanaged entity after create (persist) it in a database. That’s how I do it:
@Stateless
public class MyBean {
@EJB(name="MyController")
private MyController myController;
public MyEntity create(MyEntity entity) {
//...
myController.create(entity);
myController.preTransfer(entity);
return entity;
}
}
@Stateless
public class MyController {
@PersistenceContext(unitName = "myPU")
private EntityManager em;
public void create(MyEntity entity) {
//...
em.persist(entity);
}
public void preTransfer(MyEntity entity) {
if (em.contains(entity)) {
em.detach(entity);
}
//...
}
}
I call MyBean.create, entity successfully persisted and MyBean.create return unmanaged entity, that’s ok. But next time when I try retrieve this entity by id, it can’t be found. If I comment detach, entity can be found, but MyBean.create return managed entity in that case. Where I am wrong ?
The javadoc of
EntityManager.detachstates:So you’re persisting it, then detaching it. But the operations associated to persist have not been flushed yet, and the entity is thus not saved to the database.
Why do you want to detach it? As soon as the transaction is ended, it will be detached automatically.