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

笑着哭i 提交于 2019-12-02 19:43:22
Xavi López

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.

you can create a composite primary key in hibernate using @UniqueConstraint annotation.

@Table(name="user_group",uniqueConstraints=@UniqueConstraint(columnNames= {"userId","groupId"}))
public class user_group 
{
       @Column(name="userId")
       private String userId;

       @Column(name="groupId")
       private String group;
}

above method is not feasible if we use spring because for creating composite primary key we have to create a class is not a good thing.
in hibernate and spring you only have to create POJO classes which are available as an entity on your system.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!