I have following scenario: There are companies and employees. Each company has a set of employees. Each employee can work for several companies. So I implemented following relationships:
Company.class:
@JoinTable(name = "company_employee", joinColumns = @JoinColumn(name = "company_id") , inverseJoinColumns = @JoinColumn(name = "employee_id") )
@ManyToMany(fetch = FetchType.LAZY)
private List<Employee> employees;
Employee.class:
@JoinTable(name = "company_employee", joinColumns = @JoinColumn(name = "employee_id") , inverseJoinColumns = @JoinColumn(name = "company_id") )
@ManyToMany(fetch = FetchType.LAZY)
private List<Company> companies;
Obviously, to work for several companies, each employee should have several not overlapping schedules assigned for each company he or she works.
Also, there should be a list of schedules for each combination Company-Employee, as sometimes old schedule expires, and new schedule becomes effective.
So I also have Schedule.class
, which is supposed to have child to parent @ManyToOne
relationships both to Company
and Employee
, and should work following way: each Schedule
, and thus, List<Schedule>
should correspond to exactly one combination of Company
and Employee
instances.
How to implement this relationship?
Update 1
I only have in mind adding @OneToMany Schedule
relationship to each Company
and Employee
, but then I need to put instances of Schedule
both to Company
and Employee
each time, and this way just don't look right, also it's not obvious for me now how to fetch it back.
So any help will be appreciated.
This post was updated to show real-life scenario I have, not just generic Entity1, Entity2, Entity3 names for classes.
Update 2
I accepted the answer, but I cannot use it if Schedule contain Lists.
According to my plan, Schedule
should contain List<Vacation>
to know the set of Vacations
over a year, and List
of Days
, each of which shows start of particular week day, break, and end of this day. Those Days
are also unique for each Schedule
instance.
It was supposed to be something like below, but obviously now I don't have schedule_id
, so how to connect those lists to Schedule
?
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "schedule_id")
private List<Vacation> vacations;
@JoinTable(name = "schedule_week", joinColumns = @JoinColumn(name = "schedule_id") , inverseJoinColumns = @JoinColumn(name = "day_id") )
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Day> week;
How to include those lists right?