Why does EntityManager insert instead of updating?

不想你离开。 提交于 2019-12-04 02:54:16

This is happening because your EntityManager does not know about the object myObject.

For your code to work you should do something like this:

EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
Object myObject = em.findById(someId);
em.getTransaction().commit();
object.setName("yourNewName");
.....................
//And now run 
em.getTransaction().begin();
em.merge(myObject);
em.getTransaction().commit();
em.close();

Please note that I close the EntityManager only after I have done all my transactions needed to the database. And myObject is exactly the one that I recieved from my em.findById, I do not simply create a new object, because that will not work.

This is a tutorial that maybe can help you understand a bit more.(you have in the right a playlist with more videos about JPA ).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!