无法删除或更新父行:外键约束失败 Spring JPA
Cannot delete or update a parent row: a foreign key constraint fails Spring JPA
我有这个问题
DELETE
FROM bookings as b
WHERE b.check_out = CURRENT_DATE;
然后我得到
Cannot delete or update a parent row: a foreign key constraint fails (online_booking_app
.booked_rooms
, CONSTRAINT FK3x1lpikb2vk75nx41lxhdicvn
FOREIGN KEY (booking_id
) REFERENCES bookings
(id
))
我的 Booking 实体有 CascadeType.ALL 并通过另一方匹配映射 - 根据我的研究,这些是可能导致此消息的一些错误。
这是预订实体:
@Entity
@Table(name = "bookings")
public class BookingEntity extends BaseEntity {
@OneToMany(mappedBy = "booking",cascade = CascadeType.ALL, orphanRemoval = true)
private List<BookedRoomsEntity> bookedRooms = new ArrayList<>();
private String firstName;
private String lastName;
public List<BookedRoomsEntity> getBookedRooms() {
return bookedRooms;
}
public BookingEntity setBookedRooms(List<BookedRoomsEntity> bookedRooms) {
this.bookedRooms = bookedRooms;
return this;
}
BookedRooms实体
@Entity
@Table(name = "booked_rooms")
public class BookedRoomsEntity extends BaseEntity {
@ManyToOne()
private BookingEntity booking;
public BookingEntity getBooking() {
return booking;
}
public BookedRoomsEntity setBooking(BookingEntity booking) {
this.booking = booking;
return this;
}
CascadeType
仅适用于 EntityManager
操作。
因此您有两个选择:
- 先加载要删除的实体再使用
EntityManager.remove
- 首先使用单独的 JPQL 语句删除引用实体。
我有这个问题
DELETE
FROM bookings as b
WHERE b.check_out = CURRENT_DATE;
然后我得到
Cannot delete or update a parent row: a foreign key constraint fails (
online_booking_app
.booked_rooms
, CONSTRAINTFK3x1lpikb2vk75nx41lxhdicvn
FOREIGN KEY (booking_id
) REFERENCESbookings
(id
))
我的 Booking 实体有 CascadeType.ALL 并通过另一方匹配映射 - 根据我的研究,这些是可能导致此消息的一些错误。
这是预订实体:
@Entity
@Table(name = "bookings")
public class BookingEntity extends BaseEntity {
@OneToMany(mappedBy = "booking",cascade = CascadeType.ALL, orphanRemoval = true)
private List<BookedRoomsEntity> bookedRooms = new ArrayList<>();
private String firstName;
private String lastName;
public List<BookedRoomsEntity> getBookedRooms() {
return bookedRooms;
}
public BookingEntity setBookedRooms(List<BookedRoomsEntity> bookedRooms) {
this.bookedRooms = bookedRooms;
return this;
}
BookedRooms实体
@Entity
@Table(name = "booked_rooms")
public class BookedRoomsEntity extends BaseEntity {
@ManyToOne()
private BookingEntity booking;
public BookingEntity getBooking() {
return booking;
}
public BookedRoomsEntity setBooking(BookingEntity booking) {
this.booking = booking;
return this;
}
CascadeType
仅适用于 EntityManager
操作。
因此您有两个选择:
- 先加载要删除的实体再使用
EntityManager.remove
- 首先使用单独的 JPQL 语句删除引用实体。