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 (i.e 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