2014-12-02 95 views
0

我正在使用Spring Jpa处理Restful项目,所以我使用@Query注释。我想知道如何设置别名到我查询中的列?因为响应将resulset的每个寄存器显示为一个数组0,1,2,而不是显示我想用别名设置的自定义名称。jpql查询中列的别名

这里的一些代码

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

@Autowired 
    private DaoJuegoI iGames; 

    @RequestMapping(value="/all") 
    public @ResponseBody List<Game> all(){ 
     return iGame.allGames(); 
    } 

然后我得到这个响应..

enter image description here

而不是O我想显示id_game。 而不是1我想显示score_home_team。 而不是2我想显示日期

希望有人能帮助我!实现这一

+1

您正在使用的查询将强制JPA返回数组的集合,因此您可以根据需要将其转换为所需的表单。为什么不选择g实例而不是选定的属性,并将Game实例转换为JSON? – Chris 2014-12-03 14:10:08

+0

因为这种情况下,我需要一些属性,我认为有一种方法可以转换Json实例中的这些属性..感谢您的回答@Chris – 2014-12-03 16:39:10

回答

1

一种方式是通过定义包含这三个参数的新对象:

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

现在修改SQL @Query为 -

@Query("SELECT NEW GameResponse(g.id, g.scoreHomeTeam, g.date) FROM Game g") 
public List<Game> allGames(); 

这可以解决你的问题。