0

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.

4

1 回答 1

0

你真的需要合并吗,序列化对象时通常使用合并,如果你不需要序列化对象,你可能不需要合并。如果您从同一个 EntityManager 查询对象,您只需要更改它们然后提交。

于 2013-05-30T13:41:15.137 回答