我想从实体预订中删除行。 这个实体看起来像
@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<>();
............
}
和我的曲目
@Entity
@Table(name="repertoire")
@Data
public class Repertoire {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, unique = true)
private Integer id;
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(
name = "repertoire_seance",
joinColumns = { @JoinColumn(name = "repertoire_id")},
inverseJoinColumns = {@JoinColumn(name = "seance_id")}
)
List<Seance> seances = new ArrayList<>();
......
}
现在我有错误
Cannot delete or update a parent row: a foreign key constraint fails (`todo`.`repertoire_seance`, CONSTRAINT `FKani6veaxbp3vxruqjivg9o9sp` FOREIGN KEY (`seance_id`) REFERENCES `seance` (`id`))
我在实体关系ManyToMany中和休眠状态创建了附加表repertoire_seance。
如何避免从Seance表中删除记录,我只希望从Reservartion表中删除记录?
答案 0 :(得分:1)
您尚未发布Seance
和repository
代码,因此我会填补空白。
首先,您需要删除@OnDelete(action = OnDeleteAction.CASCADE)
注释,因为它实际上是在删除Seance
时告诉数据库删除Reservation
。
然后,您需要在Reservartion
表的外键列(@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;
...
}
最后,在您的DAO中,您需要为与要删除的Seance
相关的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);
}