jpql不起作用,但sql不起作用

ds97pgxw  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(519)

我正在使用entitymanager+hibernate,我遇到了一个问题!
我使用的代码:

public Integer getNumServicosEmAtraso() {
     try {
         Calendar calendar = Calendar.getInstance();
         calendar.add(Calendar.DAY_OF_MONTH, -2);

         String jpql = "select count(s) from Servico s where (s.indtemlaudo = false or s.indtemlaudo IS NULL) AND s.dtentrega <= :date AND s.dtEntradaRecoleta IS NOT NULL ";
         Query query = entityManager.createQuery(jpql);
         query.setParameter("date", calendar.getTime());
         return ((Long)this.getDao().getSingleResult(query)).intValue();
    } catch (Exception e) {
         log.error("Erro no getNumServicosEmAtraso", e);
    }
    return -1;
}

此代码跟踪以下日志:

Hibernate: 
    select
        count(servico0_.CODSERVICO) as col_0_0_ 
    from
        servico servico0_ 
    where
        (
            servico0_.indtemlaudo=0 
            or servico0_.indtemlaudo is null
        ) 
        and servico0_.dtentrega<=? 
        and (
            servico0_.dtEntradaRecoleta is not null
        )
353374 [http-nio-8080-exec-2] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [DATE] - [Wed Jan 03 00:00:00 BRST 2018]
353395 [http-nio-8080-exec-2] TRACE org.hibernate.type.descriptor.sql.BasicExtractor - extracted value ([col_0_0_] : [BIGINT]) - [0]

如您所见,结果是0。
如果直接在mysql数据库上运行相同的查询,则得到不同的结果:
查询:

select
    count(servico0_.CODSERVICO) as col_0_0_ 
from
    servico servico0_ 
where
    (
        servico0_.indtemlaudo=0 
        or servico0_.indtemlaudo is null
    ) 
    and servico0_.dtentrega<='Wed Jan 03 22:15:57 BRST 2018'
    and (
        servico0_.dtEntradaRecoleta is not null
    )

结果:

col_0_0_: 2

有什么建议吗?
(没有错误/例外。只是休眠跟踪日志)
谢谢您!
[更新]
我现在意识到这是行不通的:

and servico0_.dtentrega<='Wed Jan 03 22:15:57 BRST 2018'

可能只是.tostring()而不是真正的值。
用这个o得到了同样的结果:

and servico0_.dtentrega<='2018-01-03'
gt0wga4j

gt0wga4j1#

1) 当你使用 java.util.Date 在这里,请确保在实体中相应地注解该字段:

@Temporal(TemporalType.DATE)
java.util.Date dtentrega;

2) 使用重载 TemporalType 版本:

Query query = entityManager.createQuery(jpql);
query.setParameter("date", calendar.getTime(), TemporalType.DATE);

相关问题