0

I'm fairly new to hibernate and don't seem to fully understand the cascade.

So, I have the Job and the Client class and what I want to achieve is this:

  1. If I delete a client the job is deleted as well
  2. If I delete a job the client doesn't get deleted

My model looks something like this at the moment:

@Entity
public class Client {
    @Id
    @GeneratedValue
    private Long clientId;
    private String name;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Job> jobs;
}
@Entity
public class Job {
    @Id
    @GeneratedValue
    private Long jobId;
    private String title;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "client_id")
    private Client client;
    // getters, setters and some fields were omitted for brevity
}

Thank you in advance

Frank
  • 112
  • 9

1 Answers1

2

Using cascade you can perform some operations on entities transitively. If the state of one entity is changed, so it can change the state of an associated entity.

  1. If REMOVE Client -> REMOVE ALL associated Job
    You can use:

    • @OneToMany(mappedBy="client", cascade = CascadeType.REMOVE) // or you could make all operations to be cascaded with CascadeType.ALL
    • @OneToMany(mappedBy="client", orphanRemoval = true)
      Differences between them
  2. If REMOVE Job -> DON'T REMOVE associated Client
    You should exclude cascade type of REMOVE, enumerating explicitly those cascade types you need, or don't specify cascade attribute at all.

Anthony
  • 571
  • 3
  • 11