gpt4 book ai didi

java - 带复合键的 Hibernate 单向 OneToMany

转载 作者:行者123 更新时间:2023-11-30 03:26:51 27 4
gpt4 key购买 nike

我想构建 Hibernate OneToMany 关系,其中父级有一个复合主键,子级有一个主键(hibernate 自动生成)。以下是我的工作示例代码:

class Parent{

@EmbeddedId
private ParentPk parentPk;

@OneToMany( mappedBy="parent")
private List<ChildType1>;

@OneToMany( mappedBy="parent")
private List<ChildType2>;

@OneToMany( mappedBy="parent")
private List<ChildType3>;

//--setters and getters
}

@Embeddable
public class ParentPk {

private Long parentId;

private BigDecimal version;

//..setters and getters
}

class ChildType1{
@Id
private Long childId;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumns({ @JoinColumn(name = "parentId"),
@JoinColumn(name = "version") })
private Parent parent;

//..other fields and setters and getters
}

//--ChildType2 and ChildType3 like above

但现在我想将上面的模型建模为 OneToMany 单向关系,即子类不应该引用父类(想要在子类中省略 Parent 实例)。可能吗?

最佳答案

示例方法:

@Entity
class Parent {
@EmbeddedId
private ParentPk parentPk;

@OneToMany
@JoinColumns({
@JoinColumn(name = "parentId", referencedColumnName = "parentId"),
@JoinColumn(name = "version", referencedColumnName = "version")
})
private List<ChildType1> children1;

// exactly the same annotations as for children1
private List<ChildType2> children2;

// exactly the same annotations as for children1
private List<ChildType3> children3;

//..other fields and setters and getters
}

@Entity
class ChildType1 {
@Id
private Long childId;

//..other fields and setters and getters
}

//--ChildType2 and ChildType3 like above

关于java - 带复合键的 Hibernate 单向 OneToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29995509/

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