[英]Alias for columns in jpql query
I'm working in a Restful project with Spring Jpa so I'm using the @Query annotation. 我正在使用Spring Jpa在Restful项目中工作,所以我正在使用@Query注释。 I was wondering how can I set aliases to the columns in my query? 我想知道如何在查询中为列设置别名? because the response displays every register of the resulset as an array 0,1,2 instead of that I want to display the custom name that I want to set with the alias. 因为响应将结果集的每个寄存器显示为数组0,1,2而不是我想要显示我想用别名设置的自定义名称。
here's some code 这是一些代码
DaoGameI.java DaoGameI.java
public interface DaoGameI extends JpaRepository<Game, Integer> {
@Query("SELECT g.id AS id_game, g.scoreHomeTeam As score_home_team, g.date AS game_date"
" FROM Game g "
)
public List<Game> allGames();
}
ServiceGame.java ServiceGame.java
@Autowired
private DaoJuegoI iGames;
@RequestMapping(value="/all")
public @ResponseBody List<Game> all(){
return iGame.allGames();
}
then I get this response.. 然后我收到了这个回复..
instead of OI want to display id_game . 而不是OI想要显示id_game。 instead of 1 I want to display score_home_team . 而不是1我想显示score_home_team。 instead of 2 I want to display date 而不是2我想显示日期
Hope someone can help me! 希望可以有人帮帮我!
One way to achieve this is by defining a new object containing these three parameters: 实现此目的的一种方法是定义包含以下三个参数的新对象:
public class GameResponse{
private Long id_game;
private Long score_home_team;
private Date game_date;
//All getters and setters
//Add a default Constructor
//And another parameterized constructor
public GameResponse(Long id, Long score, Date date){
this.id_game = id;
this.score_home_team = score;
this.game_date = date;
}
}
Now modify your sql @Query as - 现在修改你的sql @Query为 -
@Query("SELECT NEW GameResponse(g.id, g.scoreHomeTeam, g.date) FROM Game g")
public List<Game> allGames();
This solves your problem. 这解决了您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.