Hibernate联合主键 注解方式实现

项目中遇到的问题: 用户表,标签表,用户标签关系表。其中用户标签关系表中,保存用户id和标签id,为保证数据唯一,用户id和标签id作为联合主键。分享一下过程。

1.建表语句

CREATE TABLE `bifex_nr`.`test_user_label_relation`  (
  `userId` int(11) NOT NULL,
  `labelId` int(11) NOT NULL,
  PRIMARY KEY (`userId`, `labelId`)
);

2.实体的设置 注解方式

  2.1 实体类代码

import javax.persistence.*;

@Entity
@Table(name = "test_user_label_relation")
public class TestUserLabelRelation {

    private UserLabelRelationPk relationPk;

    @Id
    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "userId", column = @Column(name = "user_id")),
            @AttributeOverride(name = "labelId", column = @Column(name = "label_id"))
    })
    public UserLabelRelationPk getRelationPk() {
        return relationPk;
    }

    public void setRelationPk(UserLabelRelationPk relationPk) {
        this.relationPk = relationPk;
    }

}

  2.2 主键类 代码 

import javax.persistence.Embeddable;
import java.io.Serializable;

@Embeddable
public class UserLabelRelationPk implements Serializable {

    private Integer userId;

    private Integer labelId;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getLabelId() {
        return labelId;
    }

    public void setLabelId(Integer labelId) {
        this.labelId = labelId;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof UserLabelRelationPk)) {
            return false;
        }

        UserLabelRelationPk key = (UserLabelRelationPk) obj;

        if (!userId.equals(key.getUserId())) {
            return false;
        }

        if (!labelId.equals(key.getLabelId())) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {

        int result = 0;

        result = userId == null ? 0 : userId.hashCode();
        result = 29 * (labelId == null ? 0 : labelId.hashCode()) + result;
        return result;
    }

}

还有其他两种实现方式 可以参考:http://www.voidcn.com/article/p-fggouqde-bam.html

 

 

你可能感兴趣的:(Hibernate联合主键 注解方式实现)