如何在JPQL中使用别名

时间:2018-06-04 09:45:59

标签: java spring spring-data-jpa h2 jpql

我试图从H2 db表中获取一些值。 执行我需要的查询是:

SELECT cast(creationDate as date) as DATE, SUM(paymentValue) as TOTAL,fxRate 
FROM payment 
group by DATE

其中" creationDate"," paymentValue"," fxRate"是表格的列#34;付款"。 CreationDate是一个时间戳,所以我只能从中获取日期。 当我尝试用Java编写它时

 @Query("SELECT cast(creationDate as date) as daydate , SUM(paymentValue) as value1, fxRate as value2 FROM payment " + 
            "group by cast(creationDate as date)")
    List<Payment> findPaymentValuePerDay ();

我收到错误[Ljava.lang.Object; cannot be cast to ...entity.Payment.

我还尝试使用一个名为GraphDto的不同对象,该对象具有daydate,value1和value2属性

@Query("SELECT cast(creationDate as date) as daydate , SUM(paymentValue) as value1, fxRate as value2 FROM payment " + 
            "group by cast(creationDate as date)")
    List<GraphDto> findPaymentValuePerDay ();

但我得到同样的错误。

 [Ljava.lang.Object; cannot be cast to ...entity.GraphDto.

那么,如何在JPQL中使用别名?我只需要一个返回3个不同列的函数。使用正确的H2查询从现有实体获取值的名称。 谢谢大家

1 个答案:

答案 0 :(得分:4)

您的查询返回Object[]而非GraphDto对象的数组,您有多种方法可以解决此问题:

解决方案1 ​​

创建一个包含daydatevalue1value2

的构造函数
@Entity
public class GraphDto{

    private Date daydate;
    private Long value1;
    private Long value2;

    public GraphDto(Date daydate, Long value1, Long value2){
        //...
    }
    //..getters and setters
}

然后您的查询应如下所示:

SELECT NEW com.packagename.GraphDto(cast(creationDate AS date), SUM(paymentValue), fxRate)
FROM payment
GROUP BY cast(creationDate AS date)

解决方案2

将返回类型更改为:

List<Object[]> findPaymentValuePerDay ();

然后在你的服务循环中通过这个对象并提取值:

List<Object[]> listObject = rep.findPaymentValuePerDay();
for(Object[] obj : listObject){
   Date date = (Date) obj[0];
   Long value1 = (Long) obj[1];
   Long value2 = (Long) obj[2];
}