java - JPQL 不工作,但 SQL 是

标签 java mysql hibernate jpql entitymanager

我在使用 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

有什么建议吗?

(没有错误/异常。只有 hibernate 跟踪日志)

谢谢!

[更新]

我现在意识到这个 WHERE 不起作用:

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

可能只是 .toString() 而这不是真正的值(value)。

使用这个 o 得到相同的结果:

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

最佳答案

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);

关于java - JPQL 不工作,但 SQL 是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123511/

相关文章:

java - 无法设置 Jenkins 的 JAVA_HOME 路径

java - 无法使用 Spring 4 和 Hibernate 4 创建与 Oracle 11g 的连接

python - 400 错误请求 : KeyError:

php - $params->在方括号之间设置数组

Hibernate JPA to DDL 命令行工具

java - 玩! framework bootstrap(Fixtures.loadModels ("initial-data.yaml)), injecting "random"模型 setter 中的字符串值

java - 如何在 Java swing 中嵌入 JavaFX SimpleSwingBrowser

java - Spring : Download file from REST controller

java - 标准化索引/搜索的字符串

mysql - 如何将子查询中的字符串连接到 MySQL 中的单行中?