2016-04-24 23 views
0

我想从多个OneToMany关系中删除一个条目,但无论我做什么都不会更新集合。春季JPA OneToMany集合不删除条目

我有三个类,Rating,Content和User。我可以成功创建适当填充内容和用户集合的评分。但是,我无法删除收藏中的评分。评分成功删除,但内容和用户集合不会更新。以下是三个类别:

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

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

+0

我实现了这两种的hashCode()和equlas()的所有三个类和集合仍然没有更新。 (我用IntelliJ发生器保证唯一的非空字段) – user3023421

+0

其实内容的评级正在更新,但由于某种原因,用户不是。奇怪,我会仔细看看为什么 – user3023421

+0

谢谢Xtreme Biker,这很有效。 – user3023421

回答

1

这看起来有点类似于你的Rating类没有适当的hashCode()equals()方法。 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(); 
} 

参见: