简体   繁体   English

如何基于Java对象的两个或多个字段为休眠生成唯一的ID?

[英]How do I generate a unique Id for hibernate based on two or more fields of a Java object?

A Java class has two 3 fields, name, roll no, and age. Java类具有两个3个字段,分别是name,roll no和age。 In the sql table there cannot be two entries with same name and roll number and different age. 在sql表中,不能有两个具有相同名称和卷号以及不同使用期限的条目。 So, while saving, by saveOrUpdate the id should map to two strings? 因此,在保存时,通过saveOrUpdate,id应该映射到两个字符串? What is an efficient way to do this? 什么是有效的方法?

You have two options here. 您在这里有两个选择。 First one is to use @IdClass , so you mark both fields as @Id, and annotate with @IdClass(ClassId.class), being ClassId a class that contains both pk fields. 第一个是使用@IdClass ,因此将两个字段都标记为@Id,并用@IdClass(ClassId.class)进行注释,将ClassId作为包含两个pk字段的类。 Here you have an example. 这里有一个例子。

Another option is to use @Embeddable and @EmbeddedId . 另一种选择是使用@Embeddable@EmbeddedId Here you have an example too. 这里也有一个例子。

While they are similar, there are a few differences among both. 尽管它们相似,但两者之间还是有一些区别。 On the case of @IdClass, you use this class for the findOne(ID id) and so on, but your original class (the one with 3 fields), doesn't contain it, as it only contains fields representing the real columns (3 fields: name, rollNo and age). 在@IdClass的情况下,可以将该类用于findOne(ID id),依此类推,但是您的原始类(具有3个字段的类)不包含该类,因为它仅包含代表真实列的字段( 3个字段:名称,rollNo和年龄。 In the case of @EmbeddedId your original class contains a field with the class representing the id fields, and not the fields representing those columns (2 fields: IdClass, age). 对于@EmbeddedId,您的原始类包含一个字段,其中的类表示id字段,而不是表示那些列的字段(2个字段:IdClass,age)。 This matters when you are using HQL, as you access fields differently. 当您使用HQL时,这一点很重要,因为您访问字段的方式有所不同。 Check the validated answer here , as it explains both options more in detail. 在此处检查经过验证的答案 ,因为它会更详细地说明这两个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM