Reputation: 119
I am trying to change the id of an persisted object .I am using JPA with Hibernate and MySQL. The error I get when executing my code is : org.hibernate.HibernateException: identifier of an instance of com.tutorial.jpa.certification.listing5_18.AA was altered from 2 to 99
I couldn't find an answer to this problem so I would appreciate your help here.The code is:
EntityManagerFactory emf=Persistence.createEntityManagerFactory("Tutorial");
EntityManager em=emf.createEntityManager();
AA aa=em.find(AA.class, 2);
em.getTransaction().begin();
aa.setId(99);
em.merge(aa);
em.getTransaction().commit();
Upvotes: 7
Views: 17534
Reputation: 8783
You should never modify the primary key of a an entity - this define the identify of the object and it makes no sense to change it.
If you really do need that - you'd be better of deleting the entity and creating a new one which just copies the old one but with a new primary key. This way, if you have any constraints - such as foreign keys pointing to the old identifier - you'll know about it.
Also check out the "Identity and Sequencing" section here.
Hope this helps.
Upvotes: 18