Is_*_*sam 5 postgresql spring hibernate jpa
用户可以根据出现值执行操作。当此值等于“ DAILY”时,我想检索最近24小时内尚未完成的所有日常操作。
有效的SQL查询:
SELECT distinct a.* FROM action as a LEFT OUTER JOIN history as h
ON a.id = h.action_id
AND h.user_id= <user> WHERE a.occurrence = 'DAILY' AND (h.id is NULL OR h.entry_date < TIMESTAMP 'yesterday')
Run Code Online (Sandbox Code Playgroud)
等效的本机查询:
@Query(value =
"SELECT distinct a.* FROM action a "
+ "LEFT OUTER JOIN history h "
+ "ON a.id = h.action_id "
+ "AND h.user_id = :userId "
+ "WHERE a.occurrence='DAILY' AND (h.id IS NULL OR h.entry_date < :yesterday) ", nativeQuery = true)
public List<Action> findAllAvailableActions(@Param("userId") Long userId, @Param("yesterday") ZonedDateTime yesterday);
Run Code Online (Sandbox Code Playgroud)
在我的服务中如何称呼它:
ZonedDateTime today = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime yesterday = today.minus(1,ChronoUnit.DAYS);
Long userId = userDTO.getId();
List<Action> result = actionRepositoryCustom.findAllAvailableActions(userId, yesterday);
Run Code Online (Sandbox Code Playgroud)
但是,我在测试中确实得到了错误的结果(已返回的操作已返回)。恐怕这链接到date参数。在我的实体中,属性entry_date声明为ZoneDateTime。我究竟做错了什么 ?
休眠状态:5.2.4
小智 5
您无法将 ZonedDateTime 传递到本机 SQL 查询中。您需要将其转换为日历:
@Query(value =
"SELECT distinct a.* FROM action a "
+ "LEFT OUTER JOIN history h "
+ "ON a.id = h.action_id "
+ "AND h.user_id = :userId "
+ "WHERE a.occurrence='DAILY' AND (h.id IS NULL OR h.entry_date < :yesterday)", nativeQuery = true)
public List<Action> findAllAvailableActions(@Param("userId") Long userId, @Param("yesterday") Calendar yesterday);
Run Code Online (Sandbox Code Playgroud)
你可以这样转换你的 ZonedDateTime :
public Calendar convertToDatabaseColumn(ZonedDateTime entityAttribute) {
if (entityAttribute == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(entityAttribute.toInstant().toEpochMilli());
calendar.setTimeZone(TimeZone.getTimeZone(entityAttribute.getZone()));
return calendar;
}
Run Code Online (Sandbox Code Playgroud)
这种方法的描述如下:链接
| 归档时间: |
|
| 查看次数: |
2877 次 |
| 最近记录: |