Java 如何在 Hibernate 中使用 UUID 作为字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22149393/
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 use UUIDs with Hibernate as a field?
提问by Florian Mozart
I'm trying to use generated UUIDs without @Id annotation, because my primary key is something else. The application does not generate an UUID, do you have an idea?
我正在尝试使用没有 @Id 注释的生成的 UUID,因为我的主键是别的东西。应用程序没有生成UUID,你有什么想法吗?
This is my declaration:
这是我的声明:
@Column(name = "APP_UUID", unique = true)
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String uuid;
I'm using Hibernate 4.3.0 with Oracle10g.
我在 Oracle10g 中使用 Hibernate 4.3.0。
采纳答案by Engineer
回答by user3173787
It's not because your UUID is a primary key that it's mandatory to have it annoted with @GeneratedValue
.
并不是因为您的 UUID 是主键,所以必须用@GeneratedValue
.
For example, you can do something like this :
例如,您可以执行以下操作:
public class MyClass
{
@Id
private String uuid;
public MyClass() {}
public MyClass (String uuid) {
this.uuid = uuid;
}
}
And in your app, generate a UUID before saving your entity :
在您的应用程序中,在保存您的实体之前生成一个 UUID:
String uuid = UUID.randomUUID().toString();
em.persist(new MyClass(uuid)); // em : entity manager
回答by Tobias Liefke
Check the Javadoc of GeneratedValue
:
检查 Javadoc GeneratedValue
:
Provides for the specification of generation strategies for the values of primary keys.
提供主键值的生成策略规范。
With other words - it is not possible with just an annotation to initialize a 'none ID' attribute.
换句话说 - 仅使用注释来初始化“无 ID”属性是不可能的。
But you can use @PrePersist
:
但你可以使用@PrePersist
:
@PrePersist
public void initializeUUID() {
if (uuid == null) {
uuid = UUID.randomUUID().toString();
}
}