0

I am trying to save to database changes made to a detached entity. The object of the entity is passed to the function by argument (named as data):

private boolean generate(CommonGameData data) {
        boolean result = true;
        EntityManager em = HibernateUtil.currentEntityManager();
        try {
            em.getTransaction().begin();

            em.merge(data);
            em.flush();
            ...some changes to data object...
            em.persist(data);
            em.flush();
            em.getTransaction().commit();

    } catch (Exception ex) {
        ...
        return false;
    }
        return true;
}

As I have read if I am using the detached entity, I should call merge first. But after commit is done successfully, I don't see any changes in database. Where is the mistake?

maximus
  • 4,201
  • 15
  • 64
  • 117
  • Perhaps related to http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge? – Smutje Feb 17 '14 at 09:21
  • What are you trying to do: save a new entity or to update it? Show us the HibernateUtil. – V G Feb 17 '14 at 09:22
  • i don't get this code. You call merge when you want to MERGE changes from an existing persisted object that has become detached. You call persist when you want to persist a newly created entity to the database. – Gimby Feb 17 '14 at 09:22
  • @AndreiI I am trying save changes of entity, which was retrieved from database before calling the function. currentEntityManager function just creates and returns new EntityManager if its closed or null (using ThreadLocal), or returns existing. – maximus Feb 17 '14 at 09:28
  • @Gimby Got it, I will try doing merge at the end of transaction before commit – maximus Feb 17 '14 at 09:30

1 Answers1

1

As you do not save a new entity (from your comment), you do not need a call to persist(). Also I do not see any reasons to make 'some changes' after calling merge(), so I called merge() after making those changes.

So, try the following:

    em.getTransaction().begin();

    ...some changes to data object...
    em.merge(data);
    em.flush();

    em.getTransaction().commit();

Also very important: if you reuse the EntityManager from the a ThreadLocal variable, you should take care of things like failed past transactions (at least clear it + maybe close it). Also if the bug still persists, try recreating an entityManager.

V G
  • 18,822
  • 6
  • 51
  • 89