无法删除或更新父行:外键约束失败 Spring JPA
我有这个查询
DELETE
FROM bookings as b
WHERE b.check_out = CURRENT_DATE;
我得到
无法删除或更新父行:外键约束失败 (
online_booking_app
.booked_rooms
, CONSTRAINTFK3x1lpikb2vk75nx41lxhdicvn
FOREIGN KEY (booking_id
)参考预订
(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;
}
预订房间实体
@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;
}
I have this query
DELETE
FROM bookings as b
WHERE b.check_out = CURRENT_DATE;
and I get
Cannot delete or update a parent row: a foreign key constraint fails (
online_booking_app
.booked_rooms
, CONSTRAINTFK3x1lpikb2vk75nx41lxhdicvn
FOREIGN KEY (booking_id
) REFERENCESbookings
(id
))
My Booking entity has CascadeType.ALL and mapped by matches the other side - from my research these are some of the mistakes that could lead to this message.
Here is the BookingEntity:
@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;
}
BookedRoomsEntity
@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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CascadeType
仅适用于EntityManager
操作。因此,您有两个选择:
EntityManager.remove
The
CascadeType
does only apply toEntityManager
operations.You therefore have two options:
EntityManager.remove