7

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();
Martinas Maria
  • 119
  • 1
  • 1
  • 8
  • 1
    Maybe you should take a look into this http://stackoverflow.com/questions/734461/hibernate-alter-identifier-primary-key – Iker Aguayo Jan 09 '14 at 11:24
  • Why change the primary key of the object? Also, if you do change the primary key of the object then how is it going to be guaranteed that it is unique? – Hrishikesh Jan 09 '14 at 15:17

1 Answers1

18

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.

Eugen
  • 8,523
  • 8
  • 52
  • 74