簡體   English   中英

彈簧(引導)與 JPA / Hibernate 和 PostgreSQL - 使用重疊日期

[英]Spring(Boot) with JPA / Hibernate and PostgreSQL - use Overlaps for dates

所以我有一個項目,我們使用 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 的日期重疊?

所以看起來你需要做三件事才能讓它發揮作用。

  1. 它可能無法使用重疊作為運算符,但幸運的是它似乎也可以用作 function: overlays overlaps(start1, end1, start2, end2)

  2. 任何 hibernate-core PostgreSQL[NN] 方言都不會映射重疊。 但它由 hibernate-spatial PostgisPG[NN]Dialects 映射的,它映射到 st_overlaps 函數以進行空間重疊。 因此,您需要使用自己的自定義方言來注冊重疊 function ,別名如下:


public class PostgisDialect extends org.hibernate.spatial.dialect.postgis.PostgisPG95Dialect {

    public PostgisDialect() {
        super();
        registerFunction("dateoverlaps", new StandardSQLFunction("overlaps", StandardBasicTypes.BOOLEAN));
    }

}

and specify it as your spring.jpa.properties.hibernate.dialect (or spring.jpa.database-platform ♂️).

  1. 您的 JPA 查詢必須包含 a = true ,如下所示:

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

您可以通過使用coalesce function 來處理空值來進一步增強這一點,即

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 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM