所以我有两个课程:游戏和用户。用户可以玩1个或多个游戏,因此它们之间有OneToMany
个关系。这是课程。
我尝试在类之间建立双向关系。
游戏:
@Entity
public class Game {
@Id
@Column(name = "GAME_NUMBER")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long gameNumber;
private int playerScore;
private int NPCScore;
private Date datetime;
@ManyToOne
@JoinColumn(name="USER_ID")
private User user;
public Game() {}
public Game(int playerScore, int nPCScore, Date datetime) {
super();
this.playerScore = playerScore;
this.NPCScore = nPCScore;
this.datetime = datetime;
}
public User getUser() {
return user;
}
} + getters & setters for attributes
用户:
@Entity
public class User {
@Id
@Column(name = "USER_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long userId;
private String username;
private String password;
@OneToMany(mappedBy="user",cascade=CascadeType.ALL)
private List<Game> games;
@ElementCollection
private List<Date> startSessions;
public User() {}
public User(String username, String password, List<Game> games, List<Date> startSessions) {
super();
this.username = username;
this.password = password;
this.games = games;
this.startSessions = startSessions;
}
}
因此,当用户玩新游戏时,下面的方法会在数据库(hsqldb
)中找到用户,然后我们将新游戏添加到列表中。因为这种关系是双向的,所以我将用户设置为每个玩过的游戏...所以这就是导致问题的原因。我能以其他方式修复吗?
@RequestMapping(value = "/game/play", method = RequestMethod.POST)
@ResponseBody
public User indexRequestPlay(@RequestParam String username, @RequestParam String password) {
User user = userRepository.findByUsernameAndPassword(username, password);
Random random = new Random();
int userScore = random.nextInt(5) + 1;
int npcScore = random.nextInt(5) + 1;
Date date = new Date();
List<Date> startSessions = user.getStartSessions();
startSessions.add(date);
user.setStartSessions(startSessions);
Game game = new Game(userScore, npcScore, date);
game.setUser(user);
List<Game> games = new ArrayList<Game>();
games.addAll(user.getGames());
games.add(game);
user.setGames(games);
userRepository.save(user);
return user;
}
我收到了这个错误:
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
和stackoverflowerror
答案 0 :(得分:1)
我认为JSON是问题.....我用JSON获得了无限递归。我添加了这个@JsonManagedReference and @JsonBackReference.
并修复了问题。你可以在这里查看完整的答案。 THX!