I am using JPA with Spring. If I allowed Spring to process transactions, then this is what my service level will look like if I assume that the EntityManager was correctly entered into the DAO:
MyService {
@Transactional
public void myMethod() {
myDaoA.doSomething();
myDaoB.doSomething();
}
}
However, if I have to execute transactions manually, I must definitely pass this EntityManager instance to each of the DAOs in the transaction. Any idea how best to reorganize this? I cry ugly by making a new MyDaoA (em) or passing em to every DAO method like doSomething (em).
MyService {
private EntityManagerFactory emf;
public void myMethod() {
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
MyDaoA myDaoA = new MyDaoA(em);
MyDaoB myDaoB = new MyDaoB(em);
try {
tx.begin();
myDaoA.doSomething();
myDaoB.doSomething();
tx.commit();
} catch(Exception e) {
tx.rollback();
}
}
}
source
share