Rar*_*res 5 jpa one-to-many spring-boot
所以我有两个类:游戏和用户。用户可以玩 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
Run Code Online (Sandbox Code Playgroud)
用户:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当用户玩新游戏时,下面的方法会在 database( 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;
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
Run Code Online (Sandbox Code Playgroud)
和 stackoverflowerror
我发现 JSON 是问题所在..... 我得到了 JSON 的无限递归。我添加了这个 @JsonManagedReference and @JsonBackReference.并解决了问题。您可以在此处查看完整答案。谢谢!
| 归档时间: |
|
| 查看次数: |
5416 次 |
| 最近记录: |