简体   繁体   中英

Saving Many-To-Many relations from both sides

I found many interesting answers in this subject but not any of them is correct for me.

Given part of Job.java

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "company_employee",
        joinColumns = @JoinColumn(name = "job_id"),
        inverseJoinColumns = @JoinColumn(name = "employee_id"))
private Set<Employee> employees = new HashSet<>();

and part of Employee.java

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "company_employee",
        joinColumns = @JoinColumn(name = "employee_id"),
        inverseJoinColumns = @JoinColumn(name = "job_id"))
private Set<Job> jobs = new HashSet<>();

How it is not working for both sides?

Creating objects:

Job job = job.builder().build();
jobRepository.save(job);

Employee employee = Employee.builder().jobs(Sets.newSet(job));
employeeRepository.save(employee);

As I do it in this way - only one side has saved ManyToMany, when tested Employee has a Job but Job does not have any Employee. Shouldn't Hibernate take care of this?`

job.getEmployees = null;
employee.getJobs = { ...job... };

I need this to be done from both sides, so when Employee is saved first, you can add him from Job side. MappedBy, Cascade, I think I've tried most of them. Also - I tried with extra "add" method but it's not working in this case, StackOverflowError...

You create two different tables for the same relation.

If you want to create bi-directional ManyToMany relation, just create one table, and with second collection use "mappedBy" attribute of @ManyToMany annotation

     @ManyToMany(mappedBy="employees", cascade = CascadeType.ALL)
     private Set<Job> jobs = new HashSet<>();

For more information check HERE

When you add annotation @JoinTable, you are telling hibernate to create a junction table between the 2 entities. Adding on both sides will mean double definition. Why is this bad? If you have 2 different definitions, which one should hibernate choose?

You don't have to save first the jobs and after the employees, if they will have cascade option, hibernate will do that for you.

How to solve null problem? If you have many to many relationship, it means that you have a bidirectional relationship and they should have references to each other.

   employee.getJobs().add(job);
   job.getEmployees().add(employee);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM