gpt4 book ai didi

java - JPA实体: How to establish relationship between Parent and multiple Child classes

转载 作者:行者123 更新时间:2023-12-01 22:31:51 25 4
gpt4 key购买 nike

我有以下 Java 类:

public Class Parent {

int someValue1;

ChildType child;
}


public Class ChildType {

int someValue2;
}


public Class ChildA extends ChildType {

int id;

String string;
}



public Class ChildB extends ChildType {

int id;

Integer integer;
}

我需要将 Parent、ChildA 和 ChildB 表示为实体 bean,每个 bean 在数据库中都有一个相关的表。

当我加载 Parent 时,我还需要根据关系加载 ChildA 或 ChildB。

最佳答案

如果我没猜错的话,类父类是一个与 ChildType 实体保持一对一关系的实体。 ChildType 也是一个抽象实体,有 2 个实现:ChildA 和 ChildB。

因此每个实体的 JPA 注释配置可能如下所示:

 Parent class as Entity
@Entity
@Table(name = "PARENT")
public class Parent { // better name will do the job, because parent is often called
// the higher level class of the same hierarchy
@Id
@GeneratedValue
@Column(name = "PARENT_ID")
private long id;

@Column(name = "SOME_VALUE") //if you need to persist it
private int someValue1;

@OneToOne(optional = false, cascade = CascadeType.ALL)
@JoinColumn(name = "FK_PARENT_ID")
private ChildType child;

// getters and setters
}
 ChildType class as Entity
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class ChildType { // this one is actually called parent class

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "CHILDTYPE_ID")
protected Long id;

@Column(name = "SOME_VALUE_2")
private int someValue2; // or maybe protected. Depends if you need childs to access it

@Column(name = "A_STRING")
private String string; // or maybe protected. Depends if you need childs to access it

// getters and setters
}

最后我们有了 ChildA 和 ChildB

如您所见,ChildType 子类上不需要有 id 字段,因为他们从 ChildType 继承这个字段!

 ChildA as Entity
@Entity
@Table(name = "CHILD_A")
public Class ChildA extends ChildType {

@Column(name = "A_STRING")
private String string;

// getters and setters
}
 ChildB as Entity
@Entity
@Table(name = "CHILD_B")
public Class ChildB extends ChildType {

@Column(name = "AN_Integer")
private Integer integer;

// getters and setters
}
<小时/>

有关 JPA 继承的更多信息

检查这里:

关于java - JPA实体: How to establish relationship between Parent and multiple Child classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27607806/

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