gpt4 book ai didi

java - Spring JPA OneToMany 集合不删除条目

转载 作者:行者123 更新时间:2023-12-01 10:00:49 64 4
gpt4 key购买 nike

我试图从多个 OneToMany 关系中删除一个条目,但是无论我做什么,它都不会更新集合。

我有三个类别:评级、内容和用户。我可以成功创建正确填充内容和用户集合的评级。但是,我无法从集合中删除评级。评级已成功删除,但内容和用户集合未更新。下面是三个类:

public class Rating {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@ManyToOne(fetch = FetchType.EAGER)
@JsonIdentityInfo(generator = JSOGGenerator.class)
private User user;

@ManyToOne(fetch = FetchType.EAGER)
@JsonIdentityInfo(generator = JSOGGenerator.class)
private Content content;

public void setUser(User user) {
this.user = user;
if (!user.getRatings().contains(this)) {
user.getRatings().add(this);
}
}

public void setContent(Content content) {
this.content = content;
if (!content.getRatings().contains(this)) {
content.getRatings().add(this);
}
}
}

public class User {
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonIdentityInfo(generator = JSOGGenerator.class)
private Set<Rating> ratings;

public void addRating(Rating rating) {
this.ratings.add(rating);
if (rating.getUser() != this) {
rating.setUser(this);
}
}

public void removeRating(Rating rating) {
ratings.remove(rating);
}
}

public class Content {
@OneToMany(mappedBy = "content", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonIdentityInfo(generator = JSOGGenerator.class)
private Set<Rating> ratings;

public void addRating(Rating rating) {
this.ratings.add(rating);
if (rating.getContent() != this) {
rating.setContent(this);
}
}

public void removeRating(Rating rating) {
ratings.remove(rating);
}
}

public class RatingController {
@RequestMapping(value = "/api/ratings/{id}", method = RequestMethod.DELETE)
public void deleteRating(@PathVariable("id") int ratingId) {
Rating rating = ratingService.getRatingById(ratingId);

if (rating == null) {
return;
}

// THIS DOES NOT DO ANYTHING
rating.getUser().removeRating(rating);

// THIS DOES NOT DO ANYTHING
rating.getContent().removeRating(rating);

ratingService.deleteRating(rating);
}
}

即使手动从集合中删除,它仍然不会更新。有什么想法吗?

最佳答案

看起来您的 Rating 类没有合适的 hashCode()equals() 方法。 Java 找不到您要删除的内容,因此它不会被删除。

您可以编写一个EntityBase,其中所有类都将具有以下公共(public)代码:

@Override
public boolean equals(Object obj) {
if (obj == null || !this.getClass().equals(obj.getClass())) {
return false;
}
return ComparisonChain.start().compare(getId(), ((EntityBase) obj).getId()).result() == 0;
}

@Override
public int hashCode() {
return (getId() == null) ? super.hashCode() : getId().intValue();
}

另请参阅:

关于java - Spring JPA OneToMany 集合不删除条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825596/

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