【问题标题】:Spring(Boot) with JPA / Hibernate and PostgreSQL - use Overlaps for dates带有 JPA / Hibernate 和 PostgreSQL 的 Spring(Boot) - 使用 Overlaps 作为日期
【发布时间】:2020-10-20 18:44:28
【问题描述】:

所以我有一个项目,我们使用 springBoot 和 PostgreSQL 10 以及 PostGis 和 hibernate.spatial 进行空间查询。到目前为止一切正常。

一个新的要求是找到开始结束日期与查询的开始结束日期以任何可能的方式重叠的实体(范围可能是封闭、开始重叠、中间、结束重叠)。

在 PostgreSQL 中,Overlaps 运算符似乎非常适合这项工作。

当尝试在我的 JPA-Query 中将它用于这样的实体“某事”时..

select sth from Sth sth where 1=1 and (sth.start, sth.end) overlaps (:begin, :end)
// set begin and end params..

我得到一个..

antlr.NoViableAltException: unexpected token: overlaps

antlr.NoViableAltException: unexpected AST node: (

org.postgresql.util.PSQLException: FEHLER: rt_raster_from_wkb: wkb size (5)  < min size (61)

是否可以在不编写本机查询的情况下通过 JPA 对日期使用重叠?

【问题讨论】:

    标签: java postgresql hibernate postgis hibernate-spatial


    【解决方案1】:

    看来你需要做三件事才能让它发挥作用。

    1. 可能无法将重叠用作运算符,但幸运的是它似乎也可以用作函数:overlaps(start1, end1, start2, end2)

    2. 任何 hibernate-core PostgreSQL[NN] 方言都不会映射重叠。但它映射到 hibernate-spatial PostgisPG[NN]Dialects,它映射到 st_overlaps 函数以进行空间重叠。因此,您需要使用自己的自定义方言来注册重叠函数,如下所示:


    public class PostgisDialect extends org.hibernate.spatial.dialect.postgis.PostgisPG95Dialect {
    
        public PostgisDialect() {
            super();
            registerFunction("dateoverlaps", new StandardSQLFunction("overlaps", StandardBasicTypes.BOOLEAN));
        }
    
    }
    

    并将其指定为您的spring.jpa.properties.hibernate.dialect(或spring.jpa.database-platform?‍♂️)。

    1. 您的 JPA 查询必须包含 = true,如下所示:

    select sth from Sth sth where 1=1 and dateoverlaps(sth.start, sth.end, :begin, :end) = true
    

    您可以通过使用coalesce 函数来处理空值来进一步增强这一点,即

    select sth from Sth sth where 1=1 and dateoverlaps(coalesce(sth.start, sth.plannedStart), coalesce(sth.end, '3999-01-01'), :begin, :end) = true
    

    当 start 为 null 时使用 plannedStart,当 end 为 null / open 时使用 long-in-the-future-date。

    【讨论】:

      猜你喜欢
      • 2018-06-02
      • 2018-03-17
      • 2016-01-28
      • 2020-10-18
      • 2021-01-23
      • 2016-06-26
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      相关资源
      最近更新 更多