JPA 2.x, Container Managed Transaction, Container Managed Dependency Injection
Pseudocode:
@Transactional(Required)
public class EJB1 {
@PersistenceContext
EntityManager em1;
@Inject
EJB2 ejb2;
public void callSecondEjb(){
MyEntity e = ejb2.returnEntity();
}
}
@Transactional(Requires_New)
public class EJB2 {
@PersistenceContext
EntityManager em2;
public MyEntity returnEntity(){
MyEntity e = new MyEntity();
em2.persist(e);
return e;
}
}
(The code above is pseudocode. Please don't get picky on typos or stuff.)
The idea is, that an entity is created and persisted inside a nested transaction. As far as I know, each transaction has its own EntityManager. My question: Does the EntityManager of the surrounding transaction (here em1) see the returned entity as managed or detached?
A closely related problem: (again Pseudocode)
@Transactional(Required)
public class EJB1 {
@PersistenceContext
EntityManager em1;
@Inject
EJB2 ejb2;
public void callSecondEjb(){
MyEntity e = new MyEntity();
em1.persist(e);
ejb2.changeEntity(e);
e.setOtherValue(123);
}
}
@Transactional(Requires_New)
public class EJB2 {
@PersistenceContext
EntityManager em2;
public MyEntity changeEntity(MyEntity e){
em2.merge(e);
e.setValue(13);
}
}
This second example shows how a managed entity is handed over from the sourrounding transaction to the nested one. The entity is than merged into the PC of the nested transaction and changed. In java we work with references when we handle objects, so all changes will be notices by both em1 and em2. On the end of "changeEntity(e)" the nested transaction is commited.
Questions: If the surrounding transaction commits, will there be a OptimisticLock exception, or is the changed version propagated to em1? Will the behaviour be different if the version filed is exposed to the entity (by annotation a field with @Version)?