Java – delete orphan when deleting parent manytoone annotation

I have two entities related as follows

@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 am using the jparepository delete method There are constraints between patient and appoint in the database. When I remove patients, I want to remove orphans I added @ ondelete hibernate annotation, but it doesn't work for me! Can you tell me why? I want to keep this one-way relationship. Can you help me?

Solution

If you want to use associations as one-way only, you can define the opposite side of deferred loading in the field without exposing getters and setters:

@Entity
public class Patient {

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

This method applies orphan removal logic from patients to their appointments. As a reward, you can navigate from patients to appointments in HQL query

Note the mappedby property, which tells the appointment that it is responsible for association management, so you can continue to associate the appointment with the patient by setting the patient in the many-to-one relationship defined in the appointment

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>