gpt4 book ai didi

java - 更新多对多关系 hibernate 中的对象

转载 作者:行者123 更新时间:2023-11-30 07:41:55 25 4
gpt4 key购买 nike

我的应用程序有 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;

}

季节

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

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

}

在用户界面上,我有一个季节按钮,单击它可以为用户设置季节。数据库表中有一个预先存在的用户条目以及季节条目。基本上我正在使用附加的季节对象信息更新用户对象。

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 (?, ?)

最佳答案

是的,您必须从数据库加载关联的所有者。你可以看看这个answer它提供了一些关于如何优化多对多关联的机制。

但是,我发现User实际上是协会的所有者,而不是Season。而且您的映射似乎不正确:您的意思可能不是 mappedBy = "followingMatch",而是 mappedBy = "followingSeason"

第三点,您应该对集合使用复数(followingSeasonsusers)以使代码更具可读性。

关于java - 更新多对多关系 hibernate 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34532447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com