小编典典

Hibernate,更改标识符/主键

hibernate

我收到的时候我想改变我的以下异常@ID中的@Entity

identifier of an instance of com.google.search.pagerank.ItemEntity was altered from 1 to 2.

我知道我要更改表中的主键。我正在使用JPA注释。

我通过使用以下单个HQL查询解决了此问题: update Table set name=:newName where name=:oldName

而不是使用更多的OO方法:

beginTransaction();
T e = session.load(...);
e.setName(newName);
session.saveOrUdate(e);
commit();

知道差异是什么吗?


阅读 324

收藏
2020-06-20

共1个答案

小编典典

我无法想象你为什么要这么做。完全没有
您为什么要更改实体的身份?您还需要更新指向它的其他表中的所有外键。似乎很痛苦,没有收获。您最好将其设置为“业务密钥”(普通属性),并使用更永久的代理密钥。我有种感觉,那就是您要解决所有这些错误,但是如果您坚持要…

本质上,您正在做的是创建一个新的Customer并删除旧的Customer,这就是我在Hibernate中实现它的方式。

[伪代码]

Begin Transaction

// create new customer from old
newC = Session.Load<Customer>(42)
Session.Evict(newC)
newC.Id = 1492
Session.Save(newC)

// update other relationships to point to newC
// ....

// delete old customer
oldC = Session.Load<Customer>(42)
Session.Delete(oldC)

Commit Transaction

但是,最好只在一个简单的单个SQL事务中一次完成所有操作,并且在任何一种情况下,您都冒着并行进程已经具有“老”
Customer实例的风险,这可能会导致一些错误。

2020-06-20