OneToMany 关系中的 StackoverflowError JPA

StackoverflowError JPA in OneToMany relationship

所以我有 2 类:游戏和用户。用户可以玩 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

Whosebugerror

我发现 JSON 是问题所在......我用 JSON 得到了无限递归。我添加了 @JsonManagedReference and @JsonBackReference. 并解决了问题。您可以在此处查看完整答案。谢谢!