Delete orphans when deleting parent manyToOne annotaion

Student :

I have two entities, related as below

@Entity
@Table(name = "APPOINTMENT")
public class Appointment {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long codeAp;

    @ManyToOne(fetch = FetchType.EAGER)
,   @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name = "codeP")
    private Patient patient;

    //attributes
    //getters and setters
    //constructors



@Entity
@Table(name = "PATIENT")
public class Patient {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long codeP;

    //attributes
    //getters and setters
    //constructors

I'm using JpaRepository delete method. There is a constraint between the tables PATIENT and APPOINTMENT in database, I want to remove orphans, when I remove Patient. I added @OnDelete hibernate annotation but it doesn't work for me! Can you please tell me why? I want to keep that unidirectional relationship, can you please help me in this?

Dragan Bozanovic :

If you want to keep using the association as unidirectional only, you can define the lazy-loaded inverse side in a field without exposing getters and setters for it:

@Entity
public class Patient {

    @OneToMany(mappedBy = "patient", orphanRemoval = true)
    private Collection<Appointment> appointments;
}

This way orphanRemoval logic is applied from patients to their appointments and as a bonus you get the ability to navigate from patients to appointments in HQL queries.

Notice the mappedBy attribute which tells that appointments are responsible for the association management, so you continue to associate appointments with patients by setting patients in the many-to-one relation defined in the Appointment.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470345&siteId=1