我的应用程序有2个通过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的季节行的所有先前存在的条目。我是否要先从数据库加载季节对象,然后再将其与用户对象一起设置?我不确定这是否是正确的方法。
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 (?, ?)
是的,您必须从数据库加载关联的所有者。您可以看一下这个答案,它提供了有关如何优化多对多关联的一些机制。
但是,我看到的User
实际上是协会的所有者,而不是Season
。似乎您的映射不正确:mappedBy = "followingMatch"
可能不是您的意思mappedBy = "followingSeason"
。
第三点,您应该对集合()使用复数形式followingSeasons
,users
以使代码更具可读性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句