gpt4 book ai didi

jpa - OneToMany 关系中的 StackoverflowError JPA

转载 作者:行者123 更新时间:2023-12-04 12:25:05 25 4
gpt4 key购买 nike

所以我有两个类:游戏和用户。用户可以玩 1 个或多个游戏,所以这是一个 OneToMany他们之间的关系。这是类(class)。

我尝试使类之间的关系双向化。

游戏:

@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

最佳答案

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

https://stackoverflow.com/a/18288939/7947794

关于jpa - OneToMany 关系中的 StackoverflowError JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44482449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com