gpt4 book ai didi

java - Spring-Data Jpa 继承 : Keeping Entity Id's in Children Entity

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:07:08 26 4
gpt4 key购买 nike

我正在处理一些具有越来越复杂的树状结构的实体,因此我决定为其创建一个抽象类,以便代码更易于维护:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class TreeStructure<T extends TreeStructure>
{
@ManyToOne
protected T parent;

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
protected Set<T> children = new HashSet<>();
//...

然后我有两个扩展它的实体:

@Entity(name = "TreeStructureOne")
public class TreeStructureOne extends TreeStructure<TreeStructureOne>
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty("TreeStructureOne_id")
private long id;

我基本上希望数据库完全不知道这个TreeStructure 抽象并保存每个 Entities 表中的所有字段并期望 InheritanceType.TABLE_PER_CLASS 来处理它。但似乎我至少需要在 TreeStructure 实体中定义 Id 否则我会得到:

初始化方法调用失败;嵌套异常是 org.hibernate.AnnotationException:没有为实体指定标识符:TreeStructure

而且我不想将 ID 添加到抽象类中,因为这会在数据库中生成三个表,分别称为:HT_TREE_STRUCTUREHT_TREE_STRUCTURE_ONEHT_TREE_STRUCTURE_TWO 各有一个字段 ID

有什么解决办法吗?

最佳答案

因为 TreeStructure 不是 @Entity,所以只使用 @MappedSuperclass

@MappedSuperclass
public abstract class TreeStructure<T extends TreeStructure> {

代替父类的 @Entity@Inheritance

您可以在 Oracle JEE API documentation 中找到 @MappedSuperclass .

关于java - Spring-Data Jpa 继承 : Keeping Entity Id's in Children Entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53303091/

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