JPA Hibernate - 更改持久对象的主键 [英] JPA Hibernate - changing the primary key of an persisted object

查看:129
本文介绍了JPA Hibernate - 更改持久对象的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改持久对象的ID。我正在使用JPA与Hibernate和MySQL。
执行代码时得到的错误是:org.hibernate.HibernateException:com.tutorial.jpa.certification.listing5_18.AA实例的标识符从2改为99



我无法找到这个问题的答案,所以我会很感激你的帮助。代码是:

  EntityManagerFactory emf = Persistence.createEntityManagerFactory(Tutorial); 
EntityManager em = emf.createEntityManager();
AA aa = em.find(AA.class,2);

em.getTransaction()。begin();
a.setId(99);
em.merge(aa);
em.getTransaction()。commit();


解决方案

一个实体 - 它定义了对象的标识,改变它是没有意义的。



如果你真的需要这样做 - 你最好删除实体并创建一个新的实体,它只是复制旧的实体,但是新的主键。这样,如果你有任何约束 - 例如指向旧标识符的外键 - 你就会知道它。

另外请查看身份和排序部分



希望这会有所帮助。

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();

解决方案

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.

这篇关于JPA Hibernate - 更改持久对象的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆