Reputation: 4516
My app has 2 java pojo classes linked via ManyToMany
relationship:
@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
class
@Entity
@Table(name = "cricket_match")
public class Season implements Serializable{
@ManyToMany(mappedBy = "followingSeason", fetch = FetchType.EAGER)
private Set<User> user;
}
On the UI I have a season button clicking on it sets the season with the user. There is a pre-existing user entry as well as the season entry in the db table. Basically I am updating the user object with an additional season object info.
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);
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 from the db & then set it with the user object? I am not sure would this be the correct approach.
public void followSeason(User loggedInUser){
sessionFactory.getCurrentSession().update(loggedInUser);
}
From the logs
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 (?, ?)
Upvotes: 1
Views: 653
Reputation: 23562
Yes, you have to load the owner of the association from the db. You can take a look at this answer which provides some mechanisms about how to optimize many-to-many associations.
However, I see that the User
is actually the owner of the association, not Season
. And it seems that your mappings are not correct: instead of mappedBy = "followingMatch"
you probably mean mappedBy = "followingSeason"
.
Third point, you should use plural for collections (followingSeasons
, users
) to make the code more readable.
Upvotes: 1