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?

5
  • Perhaps related to stackoverflow.com/questions/1069992/…? Commented Feb 17, 2014 at 9:21
  • What are you trying to do: save a new entity or to update it? Show us the HibernateUtil. Commented Feb 17, 2014 at 9: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. Commented Feb 17, 2014 at 9: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. Commented Feb 17, 2014 at 9:28
  • @Gimby Got it, I will try doing merge at the end of transaction before commit Commented Feb 17, 2014 at 9:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.