0

I didn't really found whats the right way to open Transactions across multiple DAOs in JPA/Hibernate. Could this be a way to do it? Or are there better solutions?

EntityManager em = createEntityManager(); //from EntityManagerFactory
UserDAO userDAO = new UserDAO(em);
AddressDAO addressDAO = new AddressDAO(em);

Address address = addressDAO.find(1);
address.setZIP("1234");
User user = userDAO.find(1);

EntityTransaction tx = em.getTransaction();
tx.begin();

addressDAO.save(address);
userDAO.delete(user);    

tx.commit();
em.close();

Is it ok to create new DAOs for each Request?

user2071938
  • 2,055
  • 6
  • 28
  • 60
  • Since you are handling the lifecycle of the `EntityManager` by hand, it is OK to create the DAOs per request, IMO. – Nikos Paraskevopoulos Nov 27 '22 at 21:00
  • Anything is ok if it matches your use case and application needs. I've seen passing in the transactional context into DAO methods as an option as well in some projects. Certainly helpful if some logic needs to add customized rollback functions to make sure things are cleaned up (or say calls out to a central cache). – Chris Nov 28 '22 at 14:45

0 Answers0