0

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.

user2259555
  • 233
  • 3
  • 13
  • 24

1 Answers1

3
@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;
sanek
  • 86
  • 8
  • Thank you for replying. That is the relationship I'm implementing in the Java classes, but the part that I'm not sure about is converting it to a database, especially the relationship between Courses and Manager via the manager id which is really a foreign key. And implementing the one to many between them. – user2259555 Apr 24 '13 at 20:26
  • CREATE TABLE `courses` ( `course_id` BIGINT(10) NOT NULL AUTO_INCREMENT, `manager_id` BIGINT(20) NULL DEFAULT NULL,`lecturer_id` BIGINT(20) NULL DEFAULT NULL, – sanek Apr 25 '13 at 04:57