我的应用程序有 2 个通过 ManyToMany 关系链接的 java pojo 类 User
和 Season
:
@Entity
@Table(name = "user")
public class User implements Serializable {
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "user_season", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "season_id") })
private Set<Season> followingSeason;
Set<Season> getSeasonsWhichTheUserFollows(){
return this.followingSeason;
}
}
季节
类
@Entity
@Table(name = "season")
public class Season implements Serializable{
@ManyToMany(mappedBy = "followingSeason", fetch = FetchType.EAGER)
private Set<User> user;
}
当用户取消关注某个季节 unfollowedSeason
对象时,我将其从用户关注的季节集中删除。
Set<Season> seasonSet = user.getSeasonsWhichTheUserFollows();
seasonSet.remove(unfollowedSeason);
user.setFollowingSeason(seasonSet );
this.userService.update(user);
这会从 user_season
桥接表中删除该条目,一切都很好。但同时我也想更新数据库中 Season 实体的一些字段,以将用户数减 1。有没有办法在同一个调用中做到这一点?或者我是否必须运行单独的查询来更新季节实体?
最佳答案
不确定我是否正确,但为什么你不能直接在其中添加一些内容,例如 unfollowedSeason.setCount(unfollowedSeason.getCount() +1 )
然后更新季节?
在评论中讨论后进行编辑: 你想做的事是不可能的,因为 你不能在同一个 SQL 语句中执行更新和删除(如 over9k 所述)
关于java - Hibernate ManyToMany 映射更新非拥有方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567632/