[英]JPA entities: How to establish relationship between Parent and multiple Child classes
I have the following Java classes: 我有以下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;
}
I need to represent Parent, ChildA and ChildB as entity beans with each having a related table in the database. 我需要将Parent,ChildA和ChildB表示为实体Bean,每个实体Bean在数据库中都有一个相关表。
When I load a Parent I also need to load either ChildA or ChildB depending on the relationship. 当我加载父母时,我还需要根据关系加载ChildA或ChildB。
If i got that right, class parent is an entity that keeps a one-to-one relationship with ChildType entity. 如果我做对了,那么class parent是一个与ChildType实体保持一对一关系的实体。 Also ChildType is an abstract entity with 2 implementations, ChildA and ChildB. ChildType也是一个抽象实体,具有2个实现,ChildA和ChildB。
So the JPA annotations configuration for each one of the entities, could be like that: 因此,每个实体的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
}
As you can see there is no need to have id fields on ChildType child classes, because they inherit this field from ChildType! 如您所见,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
}
check here: 在这里检查:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.