我正在尝试从多对一关系中删除实体。它不会抛出任何错误,但似乎该项目没有被删除,我也不知道为什么。这些是我的课程:
客户实体:
public class Client extends BaseEntity<Long> {
private String name;
private String email;
private LocalDate dateOfBirth;
private LocalDate dateOfRegister;
@OneToMany(mappedBy = "client", cascade = CascadeType.ALL, fetch =
FetchType.EAGER)
private Set<Rental> rentals = new HashSet<>();
..............
}
电影实体:
public class Movie extends BaseEntity<Long>{
private String title;
private int year;
private int duration;
private String genre;
private double imdbRating;
private String trailerLink;
@OneToMany(mappedBy = "movie", cascade = CascadeType.ALL, fetch =
FetchType.EAGER)
private Set<Rental> rentals = new HashSet<>();
..................
}
出租(链接)实体:
public class Rental implements Serializable {
@Id
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "movie_id")
private Movie movie;
@Id
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "client_id")
private Client client;
@Column(name = "dateRented")
private LocalDate dateRented;
@Column(name = "dateDue")
private LocalDate dateDue;
.............
}
PrimaryKey类:
public class RentalPK implements Serializable {
private Movie movie;
private Client client;
}
在控制器中,我执行以下操作:
@Override
public void deleteRental(RentalPK rentalPK) {
try {
rentalRepository.deleteById(rentalPK);
} catch (Exception e) {
throw e;
}
}
有人可以解释为什么它不删除吗?
答案 0 :(得分:1)
已解决!似乎是由于Movie和Client实体中的CascadeType.ALL。似乎CascadeType.ALL还包含CascadeType.PERSIST,它表示只能从父级中删除链接实体(在我的情况下为租用)。因此,我通过用CascadeType.ALL
代替CascadeType.REMOVE
来解决了这个问题。
编辑:我不知道这是否是确切的解释,但是它起作用了。