spring - PostgresQL + Spring JPA : org. postgresql.util.PSQLException:错误:无法将类型 bytea 转换为没有时区的时间戳

标签 spring postgresql spring-boot jpa spring-data-jpa

当有时日期范围可能有空值时如何根据日期范围选择行(选择所有行)

我有一个名为 Project(id, name, certification_date) 的表; id 是 int,name 是 varchar(250),certification_date 是时间戳。

然后插入项目时,只插入id和name,但certification_date为空。稍后用户可以对项目进行认证,然后使用 certification_date 更新该行,其中包含用户对项目进行认证的日期。因此,在项目表中,我可以有一些行的 certification_date 为空,一些行有日期(例如 2020-06-18 00:12:07)

现在我有一个带有名称的搜索查询,并且有一个 startDate 和 endDate 过滤器来过滤 certification_date。下面是带有完整签名的存储库查询。

@Query(value = "select distinct p.id, p.name, p.certification_date from project p WHERE (LOWER(p.name) LIKE CONCAT('%',LOWER(:searchKey),'%') and ((cast(:startDate as timestamp) is null or p.CERTIFICATION_DATE >= :startDate) AND (cast(:endDate as timestamp) is null or p.CERTIFICATION_DATE < :endDate ))",  nativeQuery = true)
public List<Object[]> searchProjects(@Param("searchKey") String searchKey, @Param("startDate") Date startDate, @Param("endDate") Date endDate);

因此,当 searchProjects() 使用所有值执行时,它会正确返回结果。但是当我不需要日期过滤器时,即 startDate 和 endDate 为空时,它会失败。 (这里我们对 searchKey 没有任何问题,因为如果 searchKey 为 null 我传递 ""所以它返回所有值)

异常(exception)是

org.postgresql.util.PSQLException: ERROR: cannot cast type bytea to timestamp without time zone

那么我需要做什么才能使 startDate 和 endDate 成为可选的,以便如果这些日期未通过,则只返回所有(无论 certification_date 是否为 null 或具有某些值)行?

我也尝试过 Stackoverflow 的许多解决方案,但它们对我不起作用。

最佳答案

  1. JPA无法区分'null'的值,尤其是PostgreSQL中'date, timestamp, timestamptz'类型的映射。
  2. 我的解决方案如下:
    @Query(value = "select distinct p.id, p.name, p.certification_date from project p " +
            "where LOWER(p.name) LIKE CONCAT('%',LOWER(:searchKey),'%') " +
            "and (cast(cast(:startDate as text) as timestamp) is null or p.CERTIFICATION_DATE >= :startDate) " +
            "and (cast(cast(:endDate as text) as timestamp) is null or p.CERTIFICATION_DATE < :endDate)",  nativeQuery = true)
    public List<Object[]> searchProjects(@Param("searchKey") String searchKey, @Param("startDate") Date startDate, @Param("endDate") Date endDate);

关于spring - PostgresQL + Spring JPA : org. postgresql.util.PSQLException:错误:无法将类型 bytea 转换为没有时区的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63014177/

相关文章:

java - 如何将 ArrayList 从 Jsp 传递到 Spring(注释基础) Controller

Spring Websocket 配置 : using WebSocketMessageBrokerConfigurationSupport and WebSocketConfigurer together - how?

java - 导航菜单中不同帐户类型的不同菜单

sql - 为什么在此查询中 LIMIT 2 比 LIMIT 1 长几个数量级?

spring-boot - Spring Boot 2.3.X 和 Spring Cloud Hoxton.SR6 的 EOL

java - Spring Boot Jsp 不适用于版本 2.0.2.RELEASE

postgresql - 在 sql 中使用 Windows 函数运行总计对于相同的数据具有相同的结果

ruby-on-rails - 如何在不使用 EVAL 的情况下将字符串转换为散列

java - 具有不同名称的Spring json map元素要列出

spring-boot - 使用 spring.io 演示项目时 spring boot 出错