0
一個多對一的關係數據庫保存實體名單上有2類:Game
和User
在具有JPA
User
擁有的遊戲列表(多對一關係)。
如何將另一個遊戲添加到保存在數據庫中的用戶。
這是我如何做到這一點:
@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);
List<Game> games = new ArrayList<Game>();
games.add(game);
games.addAll(user.getGames());
user.setGames(games);
userRepository.save(user);
return user;
}