如何使用 jOOQ 在 PostGIS 中的多边形内 select 点?

How to select points within polygon in PostGIS using jOOQ?

我有一个 table sensor_location:

CREATE TABLE public.sensor_location (
  sensor_id INTEGER NOT NULL,
  location_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
  location_point public.geometry NOT NULL,
  CONSTRAINT sensor_location_sensor_id_fkey FOREIGN KEY (sensor_id)
    REFERENCES public.sensor(id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
    NOT DEFERRABLE
) 

我想要一个查询,它将在选定的多边形内 return sensor_id 个传感器和 location_time 个传感器。

查询应如下所示:

SELECT 
  sensor_id,
  location_time,
FROM 
  public.sensor_location
WHERE
  ST_Within(location_point, ST_Polygon(ST_GeomFromText('LINESTRING(-71.050316 48.422044,-71.070316 48.422044,-71.070316 48.462044,-71.050316 48.462044,-71.050316 48.422044)'), 0));

我如何使用 jOOQ 做到这一点?甚至可以将 jOOQ 与 PostGIS 一起使用吗?我是否必须编写自己的 sql 查询并使用 jOOQ 执行它?

我找到了 this 但我不知道如何使用它。我还是个新手 Java 程序员。

使用 jOOQ 3.16 开箱即用的 GIS 支持

从 jOOQ 3.16 (see #982) 开始,jOOQ 将为最流行的 GIS 实现提供开箱即用的支持,包括 PostGIS

与 jOOQ 一样,只需将您的查询转换为等效的 jOOQ 查询:

ctx.select(SENSOR_LOCATION.SENSOR_ID, SENSOR_LOCATION.LOCATION_TIME)
   .from(SENSOR_LOCATION)
   .where(stWithin(
       SENSOR_LOCATION.LOCATION_POINT,
       // The ST_Polygon(...) wrapper isn't really needed
       stGeomFromText("LINESTRING(...)", 0
   ))
   .fetch();

历史答案,或者仍然缺少某些东西

... 那么,使用 plain SQL 肯定会成功。这是一个例子,如何做到这一点:

ctx.select(SENSOR_LOCATION.SENSOR_ID, SENSOR_LOCATION.LOCATION_TIME)
   .from(SENSOR_LOCATION)
   .where("ST_WITHIN({0}, ST_Polygon(ST_GeomFromText('...'), 0))", 
          SENSOR_LOCATION.LOCATION_POINT)
   .fetch();

请注意如何通过使用如上所示的普通 SQL 模板机制仍然可以使用某些类型安全性

如果您运行 有很多 GIS 查询

在这种情况下,您可能想要构建自己的 API 来封装所有普通的 SQL 用法。这是一个如何开始的想法:

public static Condition stWithin(Field<?> left, Field<?> right) {
    return DSL.condition("ST_WITHIN({0}, {1})", left, right);
}

public static Field<?> stPolygon(Field<?> geom, int value) {
    return DSL.field("ST_Polygon({0}, {1})", Object.class, geom, DSL.val(value));
}

如果您还想支持将 GIS 数据类型绑定到 JDBC 驱动程序,那么确实可以使用自定义数据类型绑定:

http://www.jooq.org/doc/latest/manual/sql-building/queryparts/custom-bindings

然后您将使用自定义数据类型而不是上面的 Object.class,然后您可以使用 Field<YourType> 而不是 Field<?> 以获得额外的类型安全。

我找到了 jooq-postgis-spatial 空间支持:https://github.com/dmitry-zhuravlev/jooq-postgis-spatial

它允许使用 jts 或 postgis 类型处理几何图形。