Home > OS >  Hibernate not saving join column id
Hibernate not saving join column id

Time:03-14

I have a ManyToOne relationship set up. Each team can have multiple users. I'm using CascadeType.PERSIST in Team.java as I don't want user accounts deleted when team gets removed or vice versa. Is the cascade type correct for my use case?

The join column in User.java table team_id stays null after saving a Team and adding a user to this team in the controller.

Team.java

@OneToMany(mappedBy = "memberAtTeam", cascade = CascadeType.PERSIST)
private List<User> usersInTeam;

User.java

@ManyToOne
@JoinColumn(name = "team_id")
private Team memberAtTeam;

TeamController.java

Team teamInvitedTo = invite.getTeamInvitedTo(); //Returns a Team object. Works.

teamInvitedTo.getUsersInTeam().add(invitedUser); //invitedUser is a User.java object
teamRepository.save(teamInvitedTo); //Doesn't set team_id, stays null in DB

teamInviteRepository.delete(invite); //Deletes used invite, this works.

CodePudding user response:

The memberAtTeam field of invitedUser needs to point to usersInTeam when you add it to the usersInTeam collection of teamInvitedTo. Or else the foreign key column value of usersInTeam will not point to teamInvitedTo when you save it, instead it will remain null.

Team teamInvitedTo = invite.getTeamInvitedTo(); //Returns a Team object. Works.
invitedUser.setMemberAtTeam(teamInvitedTo); 
teamInvitedTo.getUsersInTeam().add(invitedUser); //invitedUser is a User.java object
teamRepository.save(teamInvitedTo); //Doesn't set team_id, stays null in DB

teamInviteRepository.delete(invite); //Deletes used invite, this works.
  • Related