gpt4 book ai didi

spring - 将日期参数传递给 native 查询

转载 作者:行者123 更新时间:2023-11-29 11:29:36 26 4
gpt4 key购买 nike

用户可以根据出现值执行操作。当此值等于“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')

等效的原生查询:

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

在我的服务中是如何调用的:

ZonedDateTime today = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime yesterday = today.minus(1,ChronoUnit.DAYS);
Long userId = userDTO.getId();
List<Action> result = actionRepositoryCustom.findAllAvailableActions(userId, yesterday);

但是,我在测试中确实得到了错误的结果(返回已经完成的操作)。恐怕这与日期参数有关。属性 entry_date 在我的实体中声明为 ZoneDateTime。我做错了什么?

hibernate : 5.2.4

最佳答案

您不能将 ZonedDateTime 传递到 native 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);

您可以这样转换您的 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;
}

这里描述了这种方法:link

关于spring - 将日期参数传递给 native 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44882658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com