使用唯一列(不是主键)来休眠多对多映射

时间:2015-02-11 17:10:20

标签: hibernate

我有2个表与多对多关联

A

ID (PK), A_NAME

B

ID (PK), B_CODE(UNIQUE), B_NAME

A_B

ID (PK), ID (FK to table A(ID)), CODE (FK to table B(B_CODE))

我想使用注释为这种多对多的关系配置一个hibernate类。问题是表A_BCODE(FK到表B(B_CODE))B_CODE不是主键。我以前的尝试都失败了。

1 个答案:

答案 0 :(得分:1)

最佳解决方案:

表格方案:

@Entity
@Table(name = "SCHEME")
public class Scheme implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private BigInteger id;

    @NaturalId
    @Column(name = "SCHEME_NAME")
    private String schemeName;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        @JoinTable(name = "POSITION_SCHEME", 
             joinColumns = {
                  @JoinColumn(name = "SCHEME_ID", referencedColumnName = "ID")},
             inverseJoinColumns = {
                  @JoinColumn(name = "POSITION_CODE", referencedColumnName = "CODE")}
    )
    private Set<Position> positions = new HashSet<>();
    // getter & setter
}

表位置:

@Entity
@Table(name = "POSITION")
public class Position implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private BigInteger id;

    @NaturalId
    @Column(name = "CODE")
    private String code;

    @Column(name = "POSITION_DESCRIPTION")
    private String positionDescription;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        @JoinTable(name = "POSITION_SCHEME", 
            joinColumns = {
                @JoinColumn(name = "POSITION_CODE", referencedColumnName = "CODE")},
            inverseJoinColumns = {
                @JoinColumn(name = "SCHEME_ID", referencedColumnName = "ID")}
    )
    private Set<Scheme> schemes = new HashSet<>();
}