我正在使用JPA和Hibernate框架。因为现有表有一个父表和多个基于类别的可选表。我想做两件事,
让我们说,我们要求为每个类别提供常用字段和可选字段。每件事都是一对一的。我们决定为公共字段创建主表,并将每个类别的每个子字段拆分为单独的表。
但我们的问题是如何与主表中的所有子字段建立关系?
@Entity
@Table(name ="master")
public class Master {
@Id
private int id; //auto generated
@column(name = "name")
private String name;
private Category1;// doesn't have column in the master table
private Category2;//doesn't have column in the master table
}
public class Category1 {
@Id
private int id; //auto generated
private optionalField1;
private optioalField2;
@column(name = "master_id")
private int masterId //master table foreign key
}
public class Category2 {
@Id
private int id; //auto generated
private optionalField3;
private optioalField4;
@column(name = "master_id")
private int masterId //master table foreign key
}
答案 0 :(得分:0)
您可以在子级和父级字段上使用@OneToOne关系,并在子级上使用@JoinColumn来显示他们拥有该关系。它看起来像这样:
@Entity @Table(name ="PARENT")
public class Parent{
@Id @GeneratedValue
private int id;
@OneToOne(cascade=CascadeType.ALL, mappedBy="parent")
private Child child1;
@OneToOne(cascade=CascadeType.ALL, mappedBy="parent")
private Child child2;
}
@Entity @Table(name ="CHILD")
public class Child {
@Id @GeneratedValue
private int id;
@OneToOne @JoinColumn(name="PARENT_ID")
private Parent parent;
}
注意:添加到@OneToOne关系中的“cascade = CascadeType.ALL”意味着,当持久保存父类型的实体时, Child 实体也将被保留!