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