如何在 Java Hibernate 中更新主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6952346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to update primary key in java Hibernate
提问by bojaraj G.K
I am working on Mvc architecture,I have pojo object i want change primary key please can you help me Primary key is varchar Ex:
我正在研究 Mvc 架构,我有 pojo 对象,我想更改主键,请帮助我主键是 varchar 例如:
Users users=usersDao.load("mark")
回答by Aleksi Yrttiaho
You should never change the value of the primary key. The primary key defines the identity of the object. Hibernate or any other JPA implementation cannot identify the object as the same object if the primary key has been changed. If the primary key is subject to change, you should either choose another primary key or generate a surrogate key.
您永远不应该更改主键的值。主键定义了对象的身份。如果主键已更改,则 Hibernate 或任何其他 JPA 实现都无法将对象识别为同一对象。如果主键可能会发生变化,您应该选择另一个主键或生成一个代理键。
The workaround is to
解决方法是
- Delete the existing object
- Persist the object again with a different primary key value.
- 删除现有对象
- 使用不同的主键值再次保留对象。
回答by Bogdan
as still as I understand you need to try SQL/JDBC directly. And then somehow try to invalidate the entity from hibernate inner state and all caches.
据我所知,您需要直接尝试 SQL/JDBC。然后以某种方式尝试从休眠内部状态和所有缓存中使实体无效。