I am learning to use JPA. And I'm a little confused.
According JPA EntityManager manages transactions. But a design pattern is to inject the EntityManager in DAOs. So how is possible that are different EntityManager to the same transaction?
This is the case I want to solve
I have the DAOs defined
@Repository
JPARepository1 {
@PersistenceContext
protected EntityManager em;
....
.
@Repository
JPARepository2 {
@PersistenceContext
protected EntityManager em;
....
I have a Service
@Service
public class ServiceImpl1 {
@Autowired
private JPARepository1 repo1;
@Autowired
private JPARepository2 repo2;
public void mainMethod(){
Object o= transactionalMethod1();
try{
transactionalMethod2(o);
}catch (Exception e){
transactionalMethod3(o);
}
}
private Object transactionalMethod1(){
....
}
private void transactionalMethod2(Object o){
....
}
private void transactionalMethod3(Object o){
....
}
Then from @Controller I will invoke mainMethod(). What would be the right way to do transactional to transactionalMethod1, transactionalMethod2 and transactionalMethod3,within the same Service and using the same Repository's. I would like it if there is an exeption in transactionalMethod2, this abort the transaction, but keep the transactions of transactionalMethod1 and transactionalMethod3 Thanks, sorry for my English
EntityManger
s being passed in are different? – Tim BiegeleisenEntityManager
, but for your simply case you can expect to have only one. – Tim Biegeleisen