underdog underdog - 4 years ago 227
Java Question

Updating objects in ManyToMany relationship hibernate

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download