【问题标题】:JPA query to work with daterange of postgresql使用 postgresql 日期范围的 JPA 查询
【发布时间】:2020-08-12 08:44:22
【问题描述】:

实际数据库表:

 Column |   Type    | Collation | Nullable | Default
--------+-----------+-----------+----------+---------
 room   | text      |           |          |
 during | daterange |           |          |

工作数据库查询:

select * from room_reservation where during && daterange('[2020-10-15,2020-11-14)');

实体映射:

@Column(name = "during", columnDefinition = "daterange")
private Range<Date> during;

Jpa 存储库:

@Query(value = "select r.room from Room_Occupancy r where r.during && daterange('[?1, ?2)')", nativeQuery = true)
    List<Long> findOccupiedRooms(@Param("d1") Date d1, @Param("d2") Date d2);

例外:

Caused by: org.postgresql.util.PSQLException: ERROR: invalid input syntax for type date: "?1"
  Position: 65

如何在 JPA 中编写相同的查询?

【问题讨论】:

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


    【解决方案1】:

    这里,'[?1, ?2)' 里面的字符串字面量参数不能被替换。您可以使用|| 连接为可以替换参数的字符串。

    @Query(value = "select r.room from Room_Occupancy r where r.during &&"
          + " daterange('[' || :d1 || ',' || :d2 || ')')", nativeQuery = true)
      List<Long> findOccupiedRooms(@Param("d1") Date d1, @Param("d2") Date d2);
    

    【讨论】:

      【解决方案2】:

      因为它是本机查询使用?作为参数占位符:

      @Query(value = "select r.room from Room_Occupancy r where r.during && daterange('[?, ?)')", nativeQuery = true)
      List<Long> findOccupiedRooms(@Param("d1") Date d1, @Param("d2") Date d2);
      

      【讨论】:

        【解决方案3】:

        试试这个代码:-

            @Query(value = "select r.room from Room_Occupancy r where r.during >= ?1 and r.during < ?2", nativeQuery = true)
            List<String> findOccupiedRooms(Date d1,Date d2); //d1 < d2
        

        【讨论】:

          【解决方案4】:
           @Query(value = "select r.room from Room_Occupancy r where r.during && daterange(''||'[' || :d1 ||',' || :d2 ||')' || '')", nativeQuery = true)
                  List<Long> findOccupiedRooms(@Param("d1") Date d1, @Param("d2") Date d2);
          

          成功了

          【讨论】:

          • 我不明白为什么需要额外的'' 来连接两边。我测试了它在没有它的情况下也可以工作。
          • 你能解释一下你的解决方案吗?
          猜你喜欢
          • 1970-01-01
          • 2014-06-13
          • 1970-01-01
          • 2014-05-17
          • 2023-02-08
          • 2021-07-05
          • 2017-07-22
          • 1970-01-01
          相关资源
          最近更新 更多