I'm working on a web project, trying to understand the best way to do this sort of thing over and over again:
- Read object A from the DB
- Later on, read another object (B)
- Make changes to A and B in the DB (as part of a transaction - write all the changes or none)
The old-skool JDBC-type way isn't a problem, but JPA is doing my head in.
I need there to be a clear demarcation as to where the DB changes occur, and from what I've observed any changes to managed entities will be modified the next time EntityManager.commit()
is called (no matter if a transaction was explicitly begun before the changes or not). Correct?
Is it better then to make sure all entities are never managed, and always merge()
?
I find myself having to decide between these two examples:
RepaintAction1
User user = getUser(); //non-managed entity
Car car = getCar(123); //non-managed
car.setColor("Red");
user.setLog("Paints car red");
dao.update(car, user);
RepaintDAO1
entityTransaction.begin();
entityManager.merge(car);
entityManager.merge(user);
entityTransaction.commit();
Or:
RepaintAction2 (this is the same as RepaintAction1, but with managed entities)
User user = getUser(); //managed entity
Car car = getCar(123); //managed
car.setColor("Red");
user.setLog("Paints car red");
dao.update(car, user);
RepaintDAO2
entityTransaction.begin();
entityManager.flush();
entityTransaction.commit();
The first I don't mind, but I must be missing some advantages to managed entities (which ones?). In the second I don't like the way the scope of transactions is not clear (and how is a rollback handled?).
But are these the only options (e.g. is there a way to clearly demarcate transactions using managed entities)? What is the best way to handle this?
I apologise for making this long, but I've gone through a lot of documentation that hasn't helped and I'm not even sure that what I'm observing is correct.