我有以下查询
@Override
public List<PlayerDetails> testPlayerQuerry() {
return copyPlayersToDetails(em.createNativeQuery("select player_name from player p\n"
+ "join Player_Game pg on p.player_id = pg.fk_player_id\n"
+ "join Game g on pg.fk_game_id = g.game_id\n"
+ "where g.game_id = 2").getResultList());
}
据我所知它返回String的列表?由于我得到的错误
引起:java.lang.ClassCastException:java.lang.String无法强制转换为entities.Player 在utils.SessionFacade.copyPlayersToDetails(SessionFacade.java:105)
抛出错误的类,它可以正常运行查询返回玩家字符串,例如来自玩家的返回*
private List<PlayerDetails> copyPlayersToDetails(List< Player> players) {
List<PlayerDetails> list = new ArrayList<PlayerDetails>();
Iterator i = players.iterator();
while (i.hasNext()) {
Player player = (Player) i.next();
PlayerDetails details = new PlayerDetails(player.getPlayerId(),
player.getPlayerName(), player.getPlayerRating());
list.add(details);
}
return list;
}
我如何转换此方法或如何(如果可能)我可以将存储在此String列表中的值存入JSF页面,以便我可以检索查询结果?
答案 0 :(得分:1)
您的copyPlayersToDetails()
方法需要Player
个实体列表,而不是String
列表。这就是你在这里获得ClassCastException
的原因:
Player player = (Player) i.next();
因为i.next()
返回String
。您的Java编译器没有抱怨的原因是Query.getResultList()
(不幸的是)返回原始类型列表。
您应该将原始查询更改为:
@Override
public List<PlayerDetails> testPlayerQuerry() {
return copyPlayersToDetails(em.createNativeQuery("select p.* from player p\n"
+ "join Player_Game pg on p.player_id = pg.fk_player_id\n"
+ "join Game g on pg.fk_game_id = g.game_id\n"
+ "where g.game_id = 2", Player.class).getResultList());
}
Game
表格改为写下:
@Override
public List<PlayerDetails> testPlayerQuerry() {
return copyPlayersToDetails(em.createNativeQuery("select p.* from player p\n"
+ "join Player_Game pg on p.player_id = pg.fk_player_id\n"
+ "where pg.fk_game_id = :1", Player.class).setParameter(1, 2).getResultList());
}