本文介绍了将实体列表保存在JPA中具有ManyToOne关系的数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个班级:Game
和User
User
拥有游戏列表(与ManyToOne关系).
User
has a list of games( ManyToOne relationship).
如何向已保存在数据库中的用户添加其他游戏.
How can I add another game to the user who is saved in the database.
这是我的方法:
@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;
}
推荐答案
以下是答案:
@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;
}
这篇关于将实体列表保存在JPA中具有ManyToOne关系的数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!