使用Spring和Hibernate,我可以实现自引用类和另一个类中的父/子之间的一对多关系吗?也就是说,这是自引用类:
数据库:
CREATE TABLE `employee` (
`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL,
`manager_id` BIGINT(20) NULL DEFAULT NULL,
PRIMARY KEY (`employee_id`),
CONSTRAINT `FK_MANAGER` FOREIGN KEY (`manager_id`) REFERENCES `employee`
(`employee_id`))
型号:
@Entity
@Table(name="employee")
public class Employee {
@Id
@Column(name="employee_id")
@GeneratedValue
private Long employeeId;
@Column(name="name")
private String name;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="manager_id")
private Employee manager;
@OneToMany(mappedBy="manager")
private Set<Employee> employee = new HashSet<Employee>();
现在我想为父/子(经理/员工)和另一个类创建一对多关系,如下所示:
@OneToMany(mappedBy="manager")
private List<Course> course = new ArrayList<Course>();
@OneToMany(mappedBy="lecturer")
private List<Course> courses = new ArrayList<Course>();
因此,经理和员工都会与一门或多门类(class)有关联。类(class)类(class):
@Entity
@Table(name = "courses")
@Component
public class Course implements Serializable
@ManyToOne
@JoinColumn(name="employee_id", insertable=false, updatable=false)
private Employee employee;
@ManyToOne
@JoinColumn(name="manager_id", insertable=false, updatable=false)
private Employee manager;
这是我正在尝试实现的概述,但我想知道这是否可能,如果可以的话,我将如何在数据库关系中设置它,并能够通过 hibernate 将关系保存到数据库。
最佳答案
@OneToMany(mappedBy="manager")
private List<Course> managedCourses = new ArrayList<Course>();
@OneToMany(mappedBy="lecturer")
private List<Course> lectuedCourses = new ArrayList<Course>();
...
@Entity
@Table(name = "courses")
@Component
public class Course implements Serializable
@ManyToOne
@JoinColumn(name="lecturer_id", insertable=false, updatable=false)
private Employee lecturer;
@ManyToOne
@JoinColumn(name="manager_id", insertable=false, updatable=false)
private Employee manager;
关于mysql - 向自引用父/子添加一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16184580/