简体   繁体   中英

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. In the sql table there cannot be two entries with same name and roll number and different age. So, while saving, by saveOrUpdate the id should map to two strings? 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. Here you have an example.

Another option is to use @Embeddable and @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). 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). This matters when you are using HQL, as you access fields differently. Check the validated answer here , as it explains both options more in detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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