how to make two column as a primary key in hibernate annotation class

前端 未结 2 1788
猫巷女王i
猫巷女王i 2021-02-02 01:30

This is my annotation class and i want userId and groupId column both as primary key. I have found more questions (Question) about this, but didn\'t fo

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-02 02:09

    You should create a new @Embeddable class containing the 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 the @Entity as an @EmbeddedId:

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

    You could also use the @IdClass annotation to that effect.

    This excellent answer by Pascal Thivent elaborates on the details. You can also take a look at this other answer I posted to a almost identical question some time ago.

    As a side note, if you've got control over the DB structure, you might also consider avoiding composite keys. There are some reasons to do so.

提交回复
热议问题