如何使用LocalDate值查询JPA LocalDateTime字段? [英] How to query JPA LocalDateTime field with a LocalDate value?

查看:883
本文介绍了如何使用LocalDate值查询JPA LocalDateTime字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我寻找一种方法来获取在某个LocalDateTime日期创建的对象列表,该日期保存在Postgresql数据库中的TIMESTAMPTZ类型的字段中.

I search for a way to get a list of Objects created on a certain LocalDateTime date saved in the Postgresql database in a field of type TIMESTAMPTZ.

为此,我尝试使用JpaRepository:

To do so, I tried to use JpaRepository:

List<Object> findByCreationDate(LocalDate date);

但是我得到了错误:

java.lang.IllegalArgumentException: Parameter value [2020-12-12] did not match expected type [java.time.LocalDateTime (n/a)]

我还尝试自己编写具有相同结果的查询.

I also tried writing the query myself with the same result.

到目前为止我考虑过的解决方案:

The solutions I thought about so far :

  1. 要获取所有对象并使用Java进行过滤(但我不想去那里,所以没有)

  1. To get all the objects and filter in Java (but I wouldn't want to go there, so no)

要在LocalDateTime中转换LocalDate参数(但我认为在这种情况下,我只会看到在相同的确切时间创建的对象,所以不.只有在确定时间字段时,我才会考虑使用此选项是午夜).

To convert the LocalDate parameter in LocalDateTime (but I assume in this case I will see only Objects created at the same exact time, so no. I would consider this option only when I'm sure the fields of time are midnight).

要创建方法findByCreationDateBetween(LocalDateTime startOfTheDay, LocalDateTime endOfTheDay)(有趣的选项,但是我想在不修改LocalDate并将其转换为LocalDateTime的情况下进行查询).

To create a method findByCreationDateBetween(LocalDateTime startOfTheDay, LocalDateTime endOfTheDay) (interesting option, but I would like to do the query without modifying the LocalDate and converting it to LocalDateTime at the start and at the end of the day.)

我还试图找到一些能够在查询中的LocalDate中广播" LocalDateTime的函数,或者比较LocalDate和LocalDateTime的年,月和日,但未成功. creationDate的类型应保持LocalDateTime,而数据库字段应为TIMESTAMPTZ类型.

I also tried to find some functions that would be able to 'cast' the LocalDateTime in LocalDate in the query or compare the year, the month and the day of the LocalDate and LocalDateTime, but unsuccessfully. The type of creationDate should remain LocalDateTime and the database field of type TIMESTAMPTZ.

是否还有其他Jpa @Query替代方案,总的来说,这种情况下最好的方法是什么?

Are there any other Jpa @Query alternatives and overall, what would be the best approach for this case ?

推荐答案

您当前的解决方案很好. 但是在@Query中,您可以使用DATE()

Your current solution is fine. But in @Query you can cast column using DATE()

@Query(value = "SELECT * FROM Entity u WHERE DATE(creation_date) = ?1", nativeQuery = true)
List<Entity> findByCreationDate(LocalDate date);

这篇关于如何使用LocalDate值查询JPA LocalDateTime字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆