我有2个实体(User,NewsItem),其ID之间存在多对多关系(AccessedBy)
这是用户实体:-
@Entity
@Table(name = "news_user")
public class User {
private UUID id;
private Set<AccessedBy> accessors = new HashSet<AccessedBy>();
@Id
@Column(name = "id")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
@OneToMany(mappedBy = "user", cascade = {CascadeType.MERGE, CascadeType.DETACH}, orphanRemoval = true)
public Set<AccessedBy> getAccessors() {
return accessors;
}
public void setAccessors(Set<AccessedBy> accessors) {
this.accessors = accessors;
}
}
这里是新闻实体:-
@Entity
@Table(name = "news_item")
public class NewsItem {
private UUID id;
private Set<AccessedBy> accessors = new HashSet<>();
@Id
@Column(name = "id")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
@OneToMany(mappedBy = "newsItem", cascade = {CascadeType.MERGE, CascadeType.DETACH}, orphanRemoval = true)
public Set<AccessedBy> getAccessors() {
return accessors;
}
public void setAccessors(Set<AccessedBy> accessors) {
this.accessors = accessors;
}
}
这是它们之间的关系(AccessedBy):-
@Entity
@Table(name = "accessed_by")
@IdClass(AccessedById.class)
public class AccessedBy {
private User user;
private NewsItem newsItem;
private Boolean bookmarked;
private Boolean read;
private Boolean deleted;
@Id
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Id
@ManyToOne
@JoinColumn(name = "news_id", referencedColumnName = "id")
public NewsItem getNewsItem() {
return newsItem;
}
public void setNewsItem(NewsItem newsItem) {
this.newsItem = newsItem;
}
@Column(name = "bookmarked", nullable = false)
public Boolean getBookmarked() {
return bookmarked;
}
public void setBookmarked(Boolean bookmarked) {
this.bookmarked = bookmarked;
}
@Column(name = "read", nullable = false)
public Boolean getRead() {
return read;
}
public void setRead(Boolean read) {
this.read = read;
}
@Column(name = "deleted", nullable = false)
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
}
假设用户要为新闻项添加书签。对于书签,我在AccessedBy表中输入一个书签属性设置为true的记录。而且我想从AccessedBy表中删除该记录,以防用户将其取消书签。我如何有效地做到这一点?
我尝试过的事情:-
我试图从两个实体的HashSet中删除我先前插入的AccessedBy对象,但是从调试中看不到该对象。
我想删除的方式:-
User user = checkUser(authorization);
NewsItem newsItem = newsRepository.findByUniqueId(newsId);
AccessedBy accessedBy = new AccessedBy(user, newsItem, true, false, false);
user.getAccessors().remove(accessedBy);
newsItem.getAccessors().remove(accessedBy);
userRepository.saveAndFlush(user);
newsRepository.saveAndFlush(newsItem);
checkuser()检查基本身份验证并从数据库返回用户。