I have two entities:
@Entity
public class Entity1{}
@Entity
public class Entity2{
@OneToOne
protected Entity1 e1;
}
I have one method to search for Entity1
Entity1 findEntity1(some args){
EntityManager em = this.emfp.getEntityManager();
//perform search
return e1;
}
I use this method to find Entity2
Entity2 findEntity2(some args){
EntityManager em = this.emfp.getEntityManager();
e1 = findEntity1(args);
//perform search using e1 : Entity2.e1 = e1
return e2;
}
Each method has it’s own EntityManager and therefore it’s own Persistence context.
Could I use e1, returned from first method, in my second method?
While you cannot do it the way you are describing it – having different persistence contexts, you could do some tweaks to the code, effectively putting the entities in the same context. It depends on your stack if you can use all of them:
For an Java EE application, start the search from a session bean and use a container-managed
EntityManager– this will wrap the persistence context in a transaction and both entities will be kept in the same context for the duration of the transaction.For a Java SE application, you could still use transactions –
UserTransactions. You would need to control the span of the transaction manually though.Use an EXTENDED persistence context (since JPA 2.0). It only gets invalidated explicitly, so all the fetched entites will remain inside the context until you say so.
For all these solutions, you would need to change the
EntityManagerretrieval. Use the@PersistenceContextannotation in Java EE context and@PersistenceUnitto retrieve theEntityManagerFactoryin SE contextEDIT: It does not matter in how many EJBs you divide the search as long as you are staying inside the same transaction. As a rule of thumb, a transaction starts when the first EJB method is called and ends when this method returns. All methods invoked by this method will be in the same transaction.
This default behaviour may change though – the transactionality of EJB methods is defined by
annotations, so simply follow the path of the call along your beans.@TransactionAttribute