Doing all my transactions in one transaction [message #1629019] |
Sun, 22 February 2015 12:20 |
Bill Damage Messages: 5 Registered: February 2015 |
Junior Member |
|
|
EclipseLink 2.4.0 under Resin 4.0.42
Basically I want to know a better way to achieve something which works but I feel I'm doing via a kludge. I have an entity for which I effectively want to change a primary key. I know that's a no-no so my approach is to create the new key, copy the existing fields over then delete the old one. The problem is I can't figure out how to do it in 1 transaction, I get various errors along the lines of my entities not being managed etc. I want to to it in the same transaction to guarantee atomicity. So, the kludge is to clone the key, close and persist the trans, then do another one just for the delete. Sorry for the verbosity. You can see the delete code is in the "is nameChanged(...)" section.
Thanks very much in advance, and please assume skilllevel=newbie
Here we go:
[font=Courier]@WebServlet(value="/register", name="register-servlet")
public class RegServlet extends HttpServlet {
@PersistenceUnit(unitName="custom")
private EntityManagerFactory emf;
private EntityManager em;
@Inject
private UserTransaction ut;
...
private void writeUser(User userToPersist) {
User userWithSameRegId = null;
boolean nameChanged = false;
try {
ut.begin();
em = emf.createEntityManager();
Query query = em.createQuery("select u from User u where u.name = ?1");
query.setParameter(1, userToPersist.getName());
User user = null;
try {
user = (User) query.getSingleResult();
} catch (NoResultException nrx) {
userWithSameRegId = findUserFromRegId(userToPersist.get_Dev_Reg_Id());
if (userWithSameRegId != null) {
log.fine(s+"RegID Existed as: " + userWithSameRegId.getName());
user = new User();
user.setName(userToPersist.getName());
...
nameChanged = true;
} else {
log.fine(s+"New user");
user = userToPersist;
user.set_Reg_Count(1);
}
}
user.set_Reg_Date(new Date());
em.persist(user);
em.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ut.commit();
} catch (Exception commitEx) {
log.fine(commitEx.toString());
}
if (em != null && em.isOpen()) {
em.close();
}
}
if (nameChanged) {
try {
ut.begin();
em = emf.createEntityManager();
Query query = em.createQuery("select u from User u where u.name = ?1");
query.setParameter(1, userWithSameRegId.getName());
User user = null;
try {
user = (User) query.getSingleResult();
em.remove(user);
} catch (NoResultException nrx) {
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ut.commit();
} catch (Exception commitEx) {
log.fine(commitEx.toString());
}
if (em != null && em.isOpen()) {
em.close();
}
}
}
}
[/font]
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.03609 seconds