Hibernate ManyToMany映射更新非拥有方



我的应用程序有两个通过ManyToMany关系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;
  }
}

Season

@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语句中进行更新和删除(如9k以上所述)

相关内容

最新更新