将一对多关系添加到自引用父/子

时间:2013-04-24 06:10:34

标签: mysql spring hibernate

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

DB:

  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将关系保存到db。

1 个答案:

答案 0 :(得分:2)

@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;