我正在努力对共享单个表(子表)的多个表(父表)之间的关系进行建模。
给定以下父表1(其他父表2,3等类似):
@Entity
@Table (name="parent1")
public class ParentEntity1 {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// relationship with child table
@OneToMany(mappedBy = "parentId", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ChildEntity> children;
// other columns of parent 1
}
以及以下子表:
@Entity
@Table (name="children")
public class ChildEntity {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// points to the parent type; 1, 2, and so on
@Column(name="parent_type")
private Integer parentType;
@Column(name="parent_id")
private Integer parentId;
// some other data that belongs to ChildEntity
}
在创建关系时如何保留一个父对象和多个子对象?请注意,父类型是子表中的一列,并且父 ID 和子 ID 都是自动生成的。
您应该做的是将 ParentEntity 实际附加到 ChildEntity。在 JPA 中,m:1 的这种关系是通过 @JoinColumn 实现的。您不需要将父类型存储在子实体中 - 这将是糟糕设计的标志。父级的类型应尽可能接近其实体。因此,只需将其放入该实体中即可:
@Entity
@Table (name="children")
public class ChildEntity {
@Id Integer parentId;
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name="parent")
private ParentEntity parent;
// some other data that belongs to ChildEntity
//all setters and getters / lombok
}
@MappedSuperclass
public abstract class ParentEntity {
@OneToMany(mappedBy = "parentId", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ChildEntity> children;
@Column(name="parent_type")
private Integer parentType;
//all setters and getters / lombok
}
@Entity
@Table (name="parent1")
public class ParentEntity1 extends ParentEntity {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// other columns specific to parent 1
//all setters and getters / lombok
}
@Entity
@Table (name="parent2")
public class ParentEntity2 extends ParentEntity {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// other columns specific to parent 2
//all setters and getters / lombok
}
为了让父母有几个孩子,你可以这样做:
ParentEntity pOne = new ParentEntity1();
ParentEntity pTwo = new ParentEntity2();
ChildEntity c1 = new ChildEntity();
ChildEntity c2 = new ChildEntity();
ChildEntity c3 = new ChildEntity();
Set<ChildEntity> childrenOne = new HashSet<>();
childrenOne.add(c1);
childrenOne.add(c2);
Set<ChildEntity> childrenTwo = new HashSet<>();
childrenTwo.add(c3);
pOne.setChildren(childrenOne);
pOne.setType(1);
// ...
em.getTransaction().begin();
em.persist(pOne);
em.getTransaction().commit();
// ...
pTwo.setChildren(childrenTwo);
pTwo.setType(2);
// ...
em.getTransaction().begin();
em.persist(pTwo);
em.getTransaction().commit();
// ...
就这样。请注意,您永远不会实例化 ParentEntity 类(因为它是抽象的)。您可以有多个父表,其中每个父表通过 id 引用单个子表。此外,您可以通过继承 ParentEntity 将有关每个后续父实体类型的信息存储在其类中。我希望它能解决你的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)