休眠,更改标识符/主键 [英] Hibernate, alter identifier/primary key

查看:34
本文介绍了休眠,更改标识符/主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试更改 @Entity 中的 @ID 时,我收到以下异常.

I receive the following exception when I'm trying to alter my @ID in an @Entity.

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

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

I know that I'm altering the primary key in my table. I'm using JPA-annotations.

我使用这个单一的 HQL 查询解决了这个问题:update Table set name=:newName where name=:oldName

I solved this by using this single HQL query: update Table set name=:newName where name=:oldName

而不是使用更面向对象的方法:

Instead of using the more OO approach:

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

知道差异是什么吗?

推荐答案

我无法想象您为什么要这样做.在所有.为什么要更改实体的身份?您还需要更新指向它的其他表中的所有外键.好像很痛苦,没有收获.您最好将其设为业务密钥"(普通属性)并使用更永久的代理密钥.我有一种感觉,你的做法是错误的,但如果你坚持......

I can't imagine why you'd want to do that. At all. Why would you change an entity's identity? You'd also need to update all the foreign keys in other tables that point to it. Seems like a pain, with no gain. You're probably better off making this a "business key" (plain property) and using a more permanent surrogate key. I have a feeling that you're going about this all wrong, but if you insist...

本质上,您正在做的是创建一个新客户并删除旧客户,这就是我在 Hibernate 中完成它的方式.

Essentially what you're doing is creating a new Customer and deleting the old one, and that's how I'd accomplish it in 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 事务中一次性完成所有操作,并且在任何一种情况下,您都有可能拥有已经拥有旧"客户实例的并行进程,这可能会导致一些错误.

However, you're probably better off just doing it in all at once in a plain single SQL transaction, and in either case you risk having parallel processes that already have an instance of the "old" Customer, which might cause some errors.

这篇关于休眠,更改标识符/主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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