Question

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)?

Was it helpful?

Solution

Q1 Does the EntityManager of the surrounding transaction (here em1) see the returned entity as managed or detached?

A1 The returned entity is unknown to em1. See the entity as detached.


Q2 If the surrounding transaction commits, will there be a OptimisticLock exception, or is the changed version propagated to em1?

A2 There is no Exception. It looks like all changes are known to em1, because of the "call by reference".


Q2b Will the behaviour be different if the version filed is exposed to the entity (by annotation a field with @Version)?

A2b Don't know. My example had the version field exposed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top