How to make two columns as primary key in hibernation annotation class

This is my annotation class, and I want the userId and groupId displayed as the primary key. I found more questions ( Question ) about this, but could not find a corresponding answer. I have less reputation, so I can not comment on posts, so I ask my question here.

This is my code.

 import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.NaturalId; @Entity @Table(name="user_group") public class user_group { @Column(name="serviceProvider") private String serviceProvider; @Column(name="enterpriseId") private String enterpriseId; @Column(name="department") private String department; @Column(name="trunkGroupName") private String trunkGroupName; @Id @Column(name="userId") private String userId; @Column(name="groupId") private String group; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getServiceProvider() { return serviceProvider; } public void setServiceProvider(String serviceProvider) { this.serviceProvider = serviceProvider; } public String getEnterpriseId() { return enterpriseId; } public void setEnterpriseId(String enterpriseId) { this.enterpriseId = enterpriseId; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getTrunkGroupName() { return trunkGroupName; } public void setTrunkGroupName(String trunkGroupName) { this.trunkGroupName = trunkGroupName; } } 
+7
java hibernate hibernate-annotations composite-primary-key
source share
1 answer

You should create a new @Embeddable class containing PK fields:

 @Embeddable public class user_groupId implements Serializable { @Column(name="userId") private String userId; @Column(name="groupId") private String group; } 

And use it in @Entity as @EmbeddedId :

 @Entity public class user_group { @EmbeddedId user_groupId id; ... } 

You can also use the @IdClass annotation.

This excellent answer from Pascal Thivent details the details. You can also take a look at this other answer, which I posted on an almost identical question a while ago.

As a side note, if you have control over the structure of the database, you can also consider excluding composite keys. There are several reasons for this .

+18
source share

All Articles