在Spring Boot服务器后端内部,我需要在两个实体(User / Match)之间创建双向关联。用户可以有许多匹配,匹配总是包含两个用户。问题是我没有为关联属性找到正确的级联注释。
当我在MatchService中调用likeUser方法时,问题是没有更新用户的匹配列表。我创建了一个新的匹配对象,并在用户设置器匹配方法中设置用户的后向引用以匹配(将匹配添加到其匹配列表中),然后保存匹配。但是用户匹配列表的操作不会保存在数据库中。
有谁知道解决这个问题的正确方法?
以下是我的代码的简短摘录:
@Entity(name = "User_")
public class User {
@Id
@GeneratedValue
private Long id;
private String username;
@JsonIgnore
private String password;
@OneToMany(targetEntity = Match.class, cascade = CascadeType.ALL)
private List<Match> matches;
public void addMatch(Match match) {
matches.add(match);
}
}
@Entity(name = "Match_")
public class Match {
@Id
@GeneratedValue
private Long id;
/**
* User 1 is always the user who likes the other person first
*/
@ManyToOne(targetEntity = User.class, cascade = CascadeType.REFRESH)
private User user1;
/**
* User 2 is the user who has to confirm the match
*/
@ManyToOne(targetEntity = User.class, cascade = CascadeType.REFRESH)
private User user2;
public void setUser1(User user1) {
this.user1 = user1;
user1.addMatch(this);
}
public void setUser2(User user2) {
this.user2 = user2;
user2.addMatch(this);
}
public void setUsers(User user1, User user2) {
this.setUser1(user1);
this.setUser2(user2);
}
}
@Service
public class MatchService {
public void addMatch(Match match) {
matchRepository.save(match);
}
/**
* Method that is called if one user likes another.
*
* @param likedUser - the user who has been liked by initialUser
* @return - the match object that has either been created or was already existing
*/
public Match likeUser(User likedUser) {
User initialUser = userService.getCurrentUser();
//check if likedUser has already like initialUser
for (Match match : likedUser.getMatches()) {
if (match.getUser2().equals(initialUser)) {
match.confirm();
return match; // its a match
}
}
Match unconfirmedMatch = new Match();
unconfirmedMatch.setUsers(initialUser, likedUser);
addMatch(unconfirmedMatch);
return unconfirmedMatch;
}
}