将实体列表保存在JPA中具有ManyToOne关系的数据库中

时间:2017-06-11 14:43:38

标签: jpa spring-boot

我有两个课程:GameUser

User有一系列游戏(ManyToOne关系)。

如何向保存在数据库中的用户添加其他游戏。

我是这样做的:

@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;
}

1 个答案:

答案 0 :(得分:0)

以下是答案:

@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;
    /////////////////////////////////////////////////////////////////////////////////
    // aici adaug un camp in user.
    user.getStartSessions().add(new Date());
    /////////////////////////////////////////////////////////////////////////////////
    Game game = new Game(userScore, npcScore, new Date());
    game.setUser(user);
    user.getGames().add(game);
    userRepository.save(user);
    return user;
}