2017-06-11 46 views
0

一個多對一的關係數據庫保存實體名單上有2類:GameUser在具有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; 
} 

回答

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