我有以下父实体
@Entity
@Table(name = "EntityA", catalog = "mycatalog")
public class EntityA implements java.io.Serializable {
private int parentId;
private String a;
private Set<EntityB> entityBs = new HashSet<entityB>(0);
public EntityA() {
}
public EntityA(int parentId) {
this.parentId = parentId;
}
public EntityA(int parentId, String a) {
this.parentId = parentId;
this.a = a;
}
@Id
@Column(name = "PARENT_ID", unique = true, nullable = false)
public int getParentId() {
return this.parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
@Column(name = "columnA", length = 64)
public String getA() {
return this.a;
}
public void setA(String a) {
this.a = a;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "EntityA")
public Set<EntityB> getEntityBs() {
return this.entityBs;
}
public void setEntityBs(Set<EntityB> entityBs) {
this.entityBs = entityBs;
}
以及下面的子实体
@Entity
@Table(name = "EntityB", catalog = "mycatalog")
public class EntityB implements java.io.Serializable {
private int childId;
private EntityA entityA;
private String b;
public EntityB() {
}
public EntityB(int childId, EntityA entityA) {
this.eventId = eventId;
this.entityA = entityA;
}
public EntityB(int childId, EntityA entityA, String b) {
this.childId = childId;
this.entityA = entityA;
this.b = b;
}
@Id
@Column(name = "CHILD_ID", unique = true, nullable = false)
public int getChildId() {
return this.childId;
}
public void setChildId(int childId) {
this.childId = childId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PARENT_ID", nullable = false)
public EntityA getEntityA() {
return this.entityA;
}
public void setEntityA(EntityA entityA) {
this.entityA = entityA;
}
@Column(name = "columnB", length = 64)
public String getB() {
return this.b;
}
public void setB(String b) {
this.b = b;
}
}
我注意到即使我没有在父表中包含Set和OneToMany注释,查询这些实体也能正常工作。请参阅下面没有Set的父级:
@Entity
@Table(name = "EntityA", catalog = "mycatalog")
public class EntityA implements java.io.Serializable {
private int parentId;
private String a;
public EntityA() {
}
public EntityA(int parentId) {
this.parentId = parentId;
}
public EntityA(int parentId, String a) {
this.parentId = parentId;
this.a = a;
}
@Id
@Column(name = "PARENT_ID", unique = true, nullable = false)
public int getParentId() {
return this.parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
@Column(name = "columnA", length = 64)
public String getA() {
return this.a;
}
public void setA(String a) {
this.a = a;
}
}
您能解释一下差异吗?是否以及何时需要在父表中包含Set?
答案 0 :(得分:5)
您的父实体与其子女有一对多的关系。
关系是由连接列映射的,此列始终位于多方的表中,因此称为拥有方。从技术上讲,这种关系是一种单向关系,从孩子到他们的父母。
父实体的表格不包含任何关系信息,因此称为非拥有或反向。如果在父端添加了正确注释的children
字段,则JPA实现可以“模拟”双向关系,但这不是必需的。
如果您需要从父级遍历到其子级,则可以添加该字段。如果您只从子项遍历到父项,请不要添加它。
您可以注意到,非拥有方必须使用mappedBy
属性告知持久性提供程序属性名称,通过该属性名称在拥有方引用它,因此关系可以在对象级别上双向工作