【问题标题】:Springboot dynamic query with optional parameters带可选参数的 Springboot 动态查询
【发布时间】:2021-01-14 19:09:06
【问题描述】:

在下面我可以将modifedDate 设置为空值。当时它正在抛出错误 “无法提取 ResultSet;SQL [n/a];嵌套异常是 org.hibernate.exception.SQLGrammarException:无法提取 ResultSet”

即使modifiedDate 为空,我如何获取数据。某个时间日期将到来。 这是怎么做到的?

我希望下面的查询方法总是返回数据

  1. 如果 modifiedDate 为 null,则根据 adminStatus 返回。
  2. 根据 adminStatus 和 modifiedDate 返回。如果 modifiedDate 不为空。

我们可以通过构建动态查询并使用实体管理器执行来做到这一点。但我想要存储库。

@Repository
public interface AdminRepository extends JpaRepository<AdminEntity, Long> {

@Query(
     value="SELECT * from admin_entity where status=:adminStatus and modified_tsz>=:modifedDate:", 
    nativeQuery=true)
  List<AdminEntity> getAdmins(String adminStatus, Date modifedDate)
}


【问题讨论】:

标签: java spring spring-boot hibernate jpa


【解决方案1】:

试试这个

@Repository
public interface AdminRepository extends JpaRepository<AdminEntity, Long> {

@Query(
     value="SELECT * from admin_entity where status=:adminStatus
           AND  (modified_tsz>=:modifedDate OR :modifedDate is null)", 
    nativeQuery=true)
  List<AdminEntity> getAdmins(String adminStatus, Date modifedDate)
}

【讨论】:

  • 在此之后,我遇到了另一个错误。数据库是 postgres,日期为带有时区的时间戳。错误运算符不存在带时区的时间戳 >= bytea 这是错误。
  • 该错误现在取决于您的日期的数据类型。当 modifedDate 不为 null 时,您之前的代码是否有效?
  • 我已更改代码:这是错误:***** org.postgresql.util.PSQLException:错误:无法将类型 bytea 转换为带时区的时间戳。*** **** **更改代码:+ " AND (cast(:modifiedDate as timestamptz ) 为 NULL 或 ie.modified_tsz >= :modifiedDate)"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 2017-11-29
  • 2014-10-05
  • 1970-01-01
  • 2017-09-10
  • 2021-07-05
相关资源
最近更新 更多