0

I'm a new to Spring boot. I'd like to know which cascade type I have to use in this case.

I have an Employee class and a Departement.

Many Employees can work in a Departement (So i guess it's a @ManyToOne Relation) and a Department can have one or more Employees (so it's a **@OneToMany).

I want to perform some edits on the Employee class which have to be propagated to the other dependency. BUT if I delete one employee, I can't delete an entire Departement, so I have to just delete the Employee.

@Entity
public class Department
{
  @Column(nullable = false)
  private String name;
  @Id
  private String code;
  @Column(nullable = false)
  private String address;
  @Column(unique = true, nullable = false)
  private String website;
  @Column(unique = true, nullable = false)
  private String cellNumber;


  @JsonIgnore
  @OneToMany(mappedBy = "department")
  private Set<Employee> emplpoyee;
  
  //constructors, getters and setters
}

Here is the Employee Class

public class Employee
{
  @Id
  private String SSN;
  @Column(nullable = false)
  private String name;

  @Column(nullable = false)
  private String lastname;

  @Column(nullable = false)
  private String username;

  @Column(nullable = false)
  private String gender;

  @Column(unique = true, nullable = false)
  private String email;

  @Column(nullable = false)
  private String password;

  @Column(nullable = false)
  private String role;

  @ManyToOne(cascade = CascadeType.???, fetch = FetchType.LAZY)
  @JoinTable(
        name = "employee_works_in_dept",
        joinColumns = {@JoinColumn(name = "employee_SSN")},
        inverseJoinColumns = {@JoinColumn(name = "dept_code")}
)
private Department department;
}

What is that I have to replace with ??

I tried with CascadeType.ALL but it also deletes the Entire Department

SHl MRJ
  • 63
  • 10

1 Answers1

3

First of all I don't think you need a separate join table if your Employee can only be a part of one Department. If your employee can work on multiple departments then it is Many to Many relation.

When considering your question, you can simply remove your CascadeType. you don't need it in the Employee class.

If you need to delete all the employees under a Department when Department is deleted , then you can simply add your CascadeType.ALL on Department side.

There is a previous thread with better answer here. What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

  • You might be correct! BTW if a department might be deleted, I'd also like to simply put a simple NULL value in the department field in the Employee – SHl MRJ Mar 18 '21 at 15:25