在ManyToMany关系中更新对象hibernate

时间:2015-12-30 15:35:03

标签: java hibernate many-to-many

我的应用有两个通过ManyToMany关系链接的java pojo类:

@Entity
@Table(name = "user")
public class User implements Serializable {

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "user_match", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "match_id") })
    private Set<Season> followingSeason;

}

Season上课

@Entity
@Table(name = "cricket_match")
public class Season implements Serializable{

@ManyToMany(mappedBy = "followingSeason", fetch = FetchType.EAGER)
    private Set<User> user;

}

在用户界面上,我点了一个季节按钮就可以与用户一起设置季节。在db表中存在预先存在的用户条目以及季节条目。基本上我是用额外的季节对象信息更新用户对象。

if ("true".equalsIgnoreCase(followSeason)) {
Season season = new Season(); // I cannot instantiate a new season object here as it clears all the pre-existing entries of the season row of the entered season id. Do I load the season object first & then set it with the user object?
season.setSeasonId(SeasonId);
Set<Season> seasonSet = new HashSet<Season>();
seasonSet.add(season);
loggedInUser.setFollowingSeason(seasonSet); //loggedInUser is a User object
this.myService.followSeason(loggedInUser);

我不能在这里实例化一个新的季节对象,因为它清除了所输入的季节id的季节行的所有预先存在的条目。我是否首先从db&amp ;;中加载季节对象?然后用用户对象设置它?我不确定这是否是正确的方法。

public void followSeason(User loggedInUser){
        sessionFactory.getCurrentSession().update(loggedInUser);
    }

来自日志

Hibernate: delete from user_season where user_id=?
2015-12-30 18:16:03.0999 DEBUG http-bio-8080-exec-6 org.hibernate.persister.collection.AbstractCollectionPersister – Done deleting collection
2015-12-30 18:16:04.0005 DEBUG http-bio-8080-exec-6 org.hibernate.persister.collection.AbstractCollectionPersister – Inserting collection: [.User.followingSeason#1]
2015-12-30 18:16:04.0011 DEBUG http-bio-8080-exec-6 org.hibernate.SQL – insert into user_season (user_id, season_id) values (?, ?)
Hibernate: insert into user_season (user_id, season_id) values (?, ?)

1 个答案:

答案 0 :(得分:1)

是的,您必须从数据库加载关联的所有者。您可以查看此answer,其中提供了有关如何优化多对多关联的一些机制。

但是,我发现User实际上是关联的所有者,而不是Season。并且您的映射似乎不正确:代替mappedBy = "followingMatch",您可能意味着mappedBy = "followingSeason"

第三点,你应该使用复数形式的集合(followingSeasonsusers)来使代码更具可读性。