gpt4 book ai didi

java - 删除多对一关系不会持久

转载 作者:行者123 更新时间:2023-12-02 09:52:41 26 4
gpt4 key购买 nike

我正在尝试从多对一关系中删除实体。它不会抛出任何错误,但似乎该项目没有被删除,我不知道为什么。这些是我的类(class):

客户端实体:

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;

.............
}

主键类:

public class RentalPK implements Serializable {
private Movie movie;
private Client client;
}

在 Controller 中,我执行以下操作:

@Override
public void deleteRental(RentalPK rentalPK) {
try {
rentalRepository.deleteById(rentalPK);
} catch (Exception e) {
throw e;
}
}

有人可以解释一下为什么不删除吗?

最佳答案

解决了!看来这是因为 Movie 和 Client 实体中的 CascadeType.ALL 。似乎 CascadeType.ALL 还包含 CascadeType.PERSIST ,它表示链接实体(在我的例子中是租赁)只能从父级中删除。因此,我通过将 CascadeType.ALL 替换为 CascadeType.REMOVE 解决了该问题。

编辑:我不知道这是否是确切的解释,但它有效。

关于java - 删除多对一关系不会持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56208927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com