user2259555
user2259555

Reputation: 233

Adding a one to many relationship to a self reference parent/child

Using Spring and Hibernate, can I implement a one to many relationship between the parent/child in a self reference class and another class. That is, this is the self reference class:

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`))

Model:

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

Now I want to create a one to many relationship for both of the parent/child (manager/employee) and another class like this:

  @OneToMany(mappedBy="manager")
  private List<Course> course = new ArrayList<Course>();

  @OneToMany(mappedBy="lecturer")
  private List<Course> courses = new ArrayList<Course>();

So both of manager and employee will have an association with one or many courses. The course 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;

That's the overview of what I'm trying to implement but I would like to know if this is possible and if so how would I set it up in a DB relationship and and be able to save the relationship to db via hibernate.

Upvotes: 0

Views: 8860

Answers (1)

sanek
sanek

Reputation: 86

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

Upvotes: 3

Related Questions