小编典典

为自参考父母/子女添加一对多关系

hibernate

使用Spring和Hibernate,我可以在自引用类的父级/子级和另一个类之间实现一对多关系。也就是说,这是自引用类:

D B:

  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>();

因此,经理和员工都将与一个或多个课程相关联。课程课程:

  @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将关系保存到数据库。


阅读 219

收藏
2020-06-20

共1个答案

小编典典

@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;
2020-06-20