[英]How to use UUIDs with Hibernate as a field?
I'm trying to use generated UUIDs without @Id annotation, because my primary key is something else. 我正在尝试使用没有@Id注释的生成的UUID,因为我的主键是其他东西。 The application does not generate an UUID, do you have an idea? 该应用程序不会生成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. 我正在使用Hibernate 4.3.0和Oracle10g。
Check the Javadoc of GeneratedValue
: 检查GeneratedValue
的Javadoc:
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();
}
}
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.