我有两个@OneToMany双向关系的实体,如下所示:
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer companyId;
private String name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="company")
Set<Employee> employees = new LinkedHashSet<>();
员工类
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer empId;
private String name;
private String address;
private String email;
@ManyToOne
@JoinColumn(name="companyId")
Company company;
最初,我节省了2名员工,如下所示:
Employee emp= new Employee();
emp.setName("John");
emp.setEmail("John@gmail.com");
employeeRepository.save(emp);
Employee emp2= new Employee();
emp2.setName("Smith");
emp2.setEmail("smith@gmail.com");
employeeRepository.save(emp2);
现在我想保存一名为2家不同公司工作的员工,如下所示:
Company company =new Company();
company.setName("Google");
Employee emp = employeeRepository.findOne(1);
company.getEmployees().add(emp);
emp.setCompany(company);
companyRepository.save(company);
Company company2 =new Company();
company2.setName("Microsoft");
company2.getEmployees().add(emp);
emp.setCompany(company2);
companyRepository.save(company2);
它只将第二个公司ID更新为员工表。我希望将这两家公司分配给该员工。我怎么能这样做?
答案 0 :(得分:2)
这里的问题是你有一对多,显然它应该是多对多的,即。员工可以为多家公司工作,公司有很多员工。
您可以将关系更改为@ManyToMany(如果需要,可以使用@JoinTable),也可以创建另一个实体,例如,Employee和Company都具有一对多关系的CompanyEmployee。后一种方法可能更可取,因为您可以记录有关该关联的其他信息,例如start_date,结束日期等。
@Entity
@Table(name = "company_employees")
public class CompanyEmployee {
@ManyToOne
private Employee employee;
@ManyToOne
private Company company;
private Date startDate;
private Date endDate;
}