一尘不染

在单个表中的组合外键和主键上休眠一对一映射

hibernate

我有一个Catagory表,具有复合主键和外键。我的表结构就像

CREATE TABLE CATAGORY (
  CATAGORY_ID int(11) NOT NULL,
  CATAGORY_NAME varchar(50) DEFAULT NULL,
  VERSION int(11) NOT NULL,
  PARENT_ID  int(11) DEFAULT NULL,
  PRIMARY KEY (CATAGORY_ID,VERSION)
);

ALTER TABLE CATAGORY ADD CONSTRAINT FOREIGN KEY (PARENT_ID, VERSION) REFERENCES CATAGORY (CATAGORY_ID, VERSION);

我想要像这样的Catagory类的ORM映射

public class Catagory {
    @EmbeddedId
    private CatagoryPk pk ;
    @Column(name="CATAGORY_NAME")
    private String  catagoryName;

    private Catagory parentId;

    private List<Catagory> childs ;

}
@Embeddable
public class CatagoryPk {
    @Column(name="VERSION")
    private Integer version;
    @Column(name="CATEGORY_ID")
    private Integer catagoryId;
}

现在如何注释

private Catagory parentId;  
private List<Catagory> childs ;

阅读 316

收藏
2020-06-20

共1个答案

一尘不染

@JoinColumns({
    @JoinColumn(name="VERSION", referencedColumnName="VERSION"),
    @JoinColumn(name="PARENT_ID", referencedColumnName="CATAGORY_ID")
})
@ManyToOne
private Catagory parentId;

@OneToMany(mappedBy="parentId")
private List<Catagory> childs;

@IdClass而不是的版本@EmbeddableId(已通过Eclipselink 2.2.1测试):

public class CatagoryPk implements Serializable {

    private Integer version;
    private Integer catagoryId;

    public CatagoryPk() {
    }

    public CatagoryPk(Integer version, Integer catagoryId) {
        this.version = version;
        this.catagoryId = catagoryId;
    }
}

@Entity
@IdClass(CatagoryPk.class)
public class Catagory {
    @Column(name="VERSION")
    @Id private Integer version;
    @Column(name="CATAGORY_ID")
    @Id private Integer catagoryId;

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name="VERSION", referencedColumnName="VERSION", insertable=false, updatable=false),
        @JoinColumn(name="PARENT_ID", referencedColumnName="CATAGORY_ID")
    })
    private Catagory parentId;
}
2020-06-20