I am new to Spring JPA and I am having some trouble with setting foreign keys on an entity when inserting a row.
I have the following entities
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String departmentName;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "department_id")
List<Employee> employees;
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String employeeName;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "employee_id")
List<Role> roles;
@ManyToOne
@JoinColumn(name = "department_id", insertable = false, updatable = false)
private Department department;
}
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String roleName;
@ManyToOne
@JoinColumn(name = "employee_id", insertable = false, updatable = false)
private Employee employee;
@ManyToOne
@JoinColumn(name = "department_id", insertable = false, updatable = false)
private Department department;
}
And here is the Department Repository:
@Repository
public interface DepartmentRepository extends JpaRepository<Department, Integer> {
Department findById(long id);
}
With this approach, the department_id
in the employee
table and the employee_id
in the role
table is set correctly when I save a Department
object using departmentRepository.save(department)
.
But I also want it to set the department_id
in the role
table. How can this be achieved? Currently the relationship Department and Role is indirect (ie it is through Employee) but would I have to create a direct relationship between the 2 entities? I am not sure how to achieve this though. Any input will be appreciated.
Edit:
I want to model the relationship in this Entity Relationship diagram
As I see that you already using
@OneToMany(cascade = CascadeType.ALL)
So you knew that every update on Department with list Employee can do "many" things.
So Employee do the same to Roles (your list) but the magic auto save/update won't help.
Condition now:
As I understand:
You have Department that 1-n to Employee (Employee can only have 1 Department)
Employee can have many Role
As normal logic: Deparment 1-n Employee 1-n Roles
But some how you want Role have object of Department also.
So my first suggestion is change of logic code.
And second: a way to solve your problem!
when add Role to Employee, please access and add deparment_id also. (Department save List Employee, when save Employee - list Roles also save with same logic, just make sure to add it)
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.