Hibernate 不保存连接列 ID

Hibernate not saving join column id

我设置了 ManyToOne 关系。每个团队可以有多个用户。我在 Team.java 中使用 CascadeType.PERSIST,因为我不想在团队被移除时删除用户帐户,反之亦然。级联类型是否适合我的用例?

User.java table team_id 中的加入列在保存团队并在控制器中向该团队添加用户后保持为空。

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.

当您将 invitedUsermemberAtTeam 字段添加到 teamInvitedTousersInTeam 集合时,需要指向 usersInTeam。否则 usersInTeam 的外键列值在保存时不会指向 teamInvitedTo,而是保持为空。

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.