Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Hibernate - changing the primary key of an persisted object

Tags:

hibernate

jpa

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();
like image 227
Martinas Maria Avatar asked Jan 09 '14 11:01

Martinas Maria


People also ask

Can we update primary key in Hibernate?

No. Hibernate doesn't allow to change the primary key. In general, a primary key value should never change, if needs to be changed than the primary key column(s) are not good candidate(s) for a primary key.

Is @ID mandatory in JPA?

Id is required by JPA, but it is not required that the Id specified in your mapping match the Id in your database. For instance you can map a table with no id to a jpa entity. To do it just specify that the "Jpa Id" is the combination of all columns.

How can we auto generate primary key in Hibernate?

If we want to automatically generate the primary key value, we can add the @GeneratedValue annotation. This can use four generation types: AUTO, IDENTITY, SEQUENCE and TABLE. If we don't explicitly specify a value, the generation type defaults to AUTO.

How do I set primary key in entity class?

With an entity, make sure that you specify the primary key in the class hierarchy. When you specify the primary key, follow the below rules: For a simple (not complex type) primary key, specify @Id in the persistence field or persistence property or specify the key in the O/R mapping file.


1 Answers

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.

like image 64
Eugen Avatar answered Oct 19 '22 21:10

Eugen