如何计算JPA中只有两个日期之间的用户数?

时间:2017-12-12 13:19:01

标签: java hibernate jpa

我试图通过查询注释来计算JPA中两个日期之间只有一个1GB_DATA奖金的用户,但我收到了错误消息。

如何使用JPA进行操作?

我的SQL查询:

select count(client_id) from (select client_id, count(client_id) from AV_CUSTOMER_PRIZE where prize_type ='1GB_DATA' and prize_date>'08.11.2017' and prize_date<'01.12.2017' group by client_id having count(client_id)=1);

我的方法:

@Query("select count(client_id) from (select client_id, count(client_id) from AV_CUSTOMER_PRIZE where prize_type ='1GB_DATA' and prize_date> :sDate and prize_date< :eDate group by " +
            "client_id having count(client_id)=1)")
    int getCount(@Param("sDate") Date startDate, @Param("eDate") Date endDate);

错误:

QuerySyntaxException: unexpected token: ( near line 1, column 30 [select count(client_id) from (select client_id, count(client_id) from AV_CUSTOMER_PRIZE where prize_type ='1GB_DATA' and prize_date> :sDate and prize_date< :eDate group by client_id having count(client_id)=1)]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
    at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:91)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:288)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:187)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1894)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)

1 个答案:

答案 0 :(得分:1)

你可以

1)nativeQuery=true添加到@Query注释中。你可能会遇到日期参数问题。

2)仅使用内部查询并期望一个List:

@Query("select clientId, count(clientId) from AV_CUSTOMER_PRIZE 
        where prizeType ='1GB_DATA' and prizeTate> :sDate and prizeDate< :eDate 
        group by clientId having count(clientId)=1")
    List<Object[]> getCount(@Param("sDate") Date startDate, @Param("eDate") Date endDate);

然后你可以简单地在返回的列表上调用.size()。

还要记住在该查询中使用实体字段名称而不是本机db列名称

底线是您不能在JPA的from子句中使用select语句。