I'm not sure if I should be setting the object to the result of the merge and then return that, or just do a merge. I'm using the technique in the first block below but I am sometimes losing data and I don't know why.
@Override
public T save(T object) {
EntityManager em = null;
EntityTransaction tx = null;
try {
em = getEntityManager();
tx = em.getTransaction();
tx.begin();
object = em.merge(object);
tx.commit();
return object;
} catch (RuntimeException e) {
log.severe(e.getMessage());
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
} finally {
if (em != null && em.isOpen()) {
em.close();
}
}
}
Or should I do a merge this way?
@Override
public void save(T object) {
EntityManager em = null;
EntityTransaction tx = null;
try {
em = getEntityManager();
tx = em.getTransaction();
tx.begin();
object = em.merge(object);
tx.commit();
} catch (RuntimeException e) {
log.severe(e.getMessage());
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
} finally {
if (em != null && em.isOpen()) {
em.close();
}
}
}
After the top method is used the object that was passed in may get modified and then another save is done. This object has one to one and one to many relationships with other entities. Sometimes the data in one of the one-to-many entities get lost or isn't saved. But I can't reliably reproduce the problem.