我面临着这个有点奇怪的问题。 (也许我不明白)。我有以下 HQL 查询。
"select distinct b " +
"from Booking b " +
"inner join fetch b.telephoneNumber tp " +
"left join fetch tp.patients p " +
"where b.concluded = false and b.schedule.doctor.id = :did and b.bookingDate = :date";
具有以下参数。
query.setParameter("did", doctor.getId());
query.setParameter("date", date);
这里的日期
是一个Java LocalDate
。当我调用query.getResultList()
时,它不返回任何值。 (即使有与给定条件匹配的值)。然后我启用了 hibernate 调试和跟踪日志来获取相关的 SQL 查询和值。
select distinct booking0_.id as id1_1_0_, telephonen1_.id as id1_11_1_, patient3_.id as id1_4_2_, booking0_.bookingDate as bookingD2_1_0_, booking0_.bookingReference as bookingR3_1_0_, booking0_.bookingUniqueId as bookingU4_1_0_, booking0_.channelRecord_id as channelR7_1_0_, booking0_.checkedIn as checkedI5_1_0_, booking0_.checkedInPatient_id as checkedI8_1_0_, booking0_.concluded as conclude6_1_0_, booking0_.schedule_id as schedule9_1_0_, booking0_.telephone_number_id as telepho10_1_0_, telephonen1_.isActive as isActive2_11_1_, telephonen1_.number as number3_11_1_, telephonen1_.securityToken as security4_11_1_, telephonen1_.token_id as token_id6_11_1_, telephonen1_.uniqueId as uniqueId5_11_1_, patient3_.birthDay as birthDay2_4_2_, patient3_.firstName as firstNam3_4_2_, patient3_.gender as gender4_4_2_, patient3_.height as height5_4_2_, patient3_.lastName as lastName6_4_2_, patient3_.picture as picture7_4_2_, patient3_.pictureContentType as pictureC8_4_2_, patient3_.weight as weight9_4_2_, patients2_.telephonenumber_id as telephon2_5_0__, patients2_.patient_id as patient_1_5_0__
from Booking booking0_
left outer join TelephoneNumber telephonen1_ on booking0_.telephone_number_id=telephonen1_.id
left outer join Patient_TelephoneNumber patients2_ on telephonen1_.id=patients2_.telephonenumber_id
left outer join Patient patient3_ on patients2_.patient_id=patient3_.id
cross join Schedule schedule4_
where booking0_.schedule_id=schedule4_.id and booking0_.concluded=0 and schedule4_.doctor_id=? and booking0_.bookingDate=?
2020-01-12 18:58:34 TRACE binding parameter [1] as [BIGINT] - [1]
2020-01-12 18:58:34 TRACE binding parameter [2] as [DATE] - [2020-01-12]
因此,如果将这些值添加到生成的 SQL 中并直接针对数据库运行查询,则会给出两个结果(预期)。
每当我从 HQL 中删除“日期”值时,它也会给出结果。对于为什么会发生这种情况有什么想法吗?
Hibernate version: 5.4.9.Final
DB: Mysql 8
Java 11 (Open JDK)
WildFly 18.
谢谢!
最佳答案
这背后的原因是时区问题。我的应用程序服务器和数据库服务器位于两个不同的时区。因此,每当您尝试通过 JDBC 检索时,由于此 [1],它都会将您的日期转换为数据库时区。
但是直接 SQL 可以在数据库服务器上运行,并且没有时区问题。
所以我最初的方法是将以下属性添加到连接 URL(如 [1] bug 中所建议)。结果成功了。
serverTimezone=<client_time_zone>
但是,作为永久解决方案,我将数据库服务器时区更改为应用程序服务器时区。 (我知道 UTC 是正确的方法,但我更喜欢这个。)
关于java - 即使生成的 SQL 确实返回值,HQL 也不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59705343/