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();
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With