Spring JPA OneToMany集合不删除条目

时间:2016-04-24 16:05:13

标签: java spring hibernate jpa

我正在尝试从多个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);
    } 
}

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

1 个答案:

答案 0 :(得分:1)

对于hashCode()课程,您看起来没有适当的equals()Rating方法。 Java无法找到您要删除的那个,因此它不会被删除。

您可以编写一个EntityBase,所有类都将使用此公共代码:

@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();
}

另见: