Subsitute for Month,year,date functions in jpa

前端 未结 3 1907
Happy的楠姐
Happy的楠姐 2021-01-14 15:41

I want to execute this query in JPA.But i am getting error while executing this query.How to use Month(),Year() in JPA We can use these in native SQL Query.But how to use i

3条回答
  •  梦毁少年i
    2021-01-14 16:20

    Dears,

    sometimes we have to think with different way, maybe this can help:

    TypedQuery query = entityManager.createQuery(
                    "SELECT SUM(COALESCE(p.amount, 0)) FROM Payment p WHERE p.paymentDate BETWEEN ?1 AND ?2", Number.class);
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MILLISECOND, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.HOUR, 0);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.MONTH, month -1);
            calendar.set(Calendar.YEAR, year);
    
            query.setParameter(1, calendar.getTime());
            //the location is very important
            calendar.add(Calendar.MONTH, 1);
            calendar.add(Calendar.MILLISECOND, -1);
    
            query.setParameter(2, calendar.getTime());
            return query.getSingleResult().doubleValue();
    

提交回复
热议问题