gpt4 book ai didi

java - Hibernate 单表中复合外键和主键的一对一映射

转载 作者:行者123 更新时间:2023-11-29 06:36:03 29 4
gpt4 key购买 nike

我有一个 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 ;

最佳答案

@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;
}

关于java - Hibernate 单表中复合外键和主键的一对一映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24696358/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com