Java 删除带有约束的行

Java 删除带有约束的行,java,hibernate,Java,Hibernate,我想从实体保留中删除行。 这个实体看起来像 @Entity @Table(name="reservation") public class Reservation { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(nullable = false, unique = true) private Integer id; @ManyToOne(fetch = FetchType.LA

我想从实体保留中删除行。 这个实体看起来像

@Entity
@Table(name="reservation")
public class Reservation {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private Seance reservationSeance;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User userReservation;

    @OneToMany(orphanRemoval = true)
    private List<Seat> seats = new ArrayList<>();
    ............

}
我在实体关系中使用了ManyToMany和hibernate来创建额外的表曲目


如何避免从表Seance中删除记录,我只想从Reservation表中删除记录?

您还没有发布
Seance
存储库
代码,因此我将填补空白

首先,您需要删除
@OnDelete(action=ondeletection.CASCADE)
注释,因为它实际上是在删除
保留时告诉数据库删除
Seance

然后,您需要在
reservation
表的外键列(@JoinColumn)中允许空值,如下所示:

@Entity
@Table(name="Seance")
public class Seance {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer id;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "reservation_id", nullable = true)
    private Reservation reservation;

    ...
}
public void deleteReservation(int reservationId) {
    Session currentSession = sessionFactory.getCurrentSession();

    // get reservation with primary key
    Reservation reservation = currentSession.get(Reservation.class, reservationId);  
    Seance seance = reservation.getSeance();

    //set reservation_id null
    Seance.setReservation(null);

    //delete the reservation
    currentSession.remove(reservation);
}
最后,在DAO中,您需要为与要删除的
保留相关的
Seance
设置空值,然后才将其删除,如下所示:

@Entity
@Table(name="Seance")
public class Seance {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer id;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "reservation_id", nullable = true)
    private Reservation reservation;

    ...
}
public void deleteReservation(int reservationId) {
    Session currentSession = sessionFactory.getCurrentSession();

    // get reservation with primary key
    Reservation reservation = currentSession.get(Reservation.class, reservationId);  
    Seance seance = reservation.getSeance();

    //set reservation_id null
    Seance.setReservation(null);

    //delete the reservation
    currentSession.remove(reservation);
}