0

使用 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;

这是我正在尝试实现的概述,但我想知道这是否可行,如果可以,我将如何在数据库关系中设置它,并能够通过休眠将关系保存到数据库。

4

1 回答 1

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;
于 2013-04-24T17:36:53.573 回答