Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

java - How to work with alias in JPQL

I'm trying to get some values from a H2 db table. The query which does what I need is this:

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

where "creationDate", "paymentValue", "fxRate" are columns of the table "payment". CreationDate is a timestamp so I have to get only the date from it. When I try to write it in 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 ();

I get the error [Ljava.lang.Object; cannot be cast to ...entity.Payment.

I also tried to use a different object called GraphDto which has as attributes daydate, value1 and 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 ();

but I get the same error.

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

so, how can I work with alias in JPQL?? I just need a function that returns 3 different columns' name with values took from an existing entity using the right H2 query. Thank you all

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your query return an array of Object[] and not GraphDto Object, you have multiple ways to solve this problems :

Solution 1

Create a constructor which hold daydate, value1, value2

@Entity
public class GraphDto{

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

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

then your query should look like this :

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

Solution 2

change the return type to :

List<Object[]> findPaymentValuePerDay ();

Then in your service loop over this object and extract the values :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...