如何解决JPA查询可与Postgresql的日期范围一起使用
实际数据库表:
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中编写相同的查询?
解决方法
在这里,不能替换字符串文字参数中的'[?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);
,
因为它是本机查询,所以使用?作为参数占位符:
@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);
,
尝试以下代码:-
@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
,
@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);
这有效
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。