【问题标题】:How to select points within polygon in PostGIS using jOOQ?如何使用 jOOQ 在 PostGIS 中选择多边形内的点?
【发布时间】:2016-11-17 04:07:26
【问题描述】:

我有一张桌子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
) 

我想要一个查询,它将返回 sensor_ids 的传感器和 location_times 在选定的多边形内。

查询应该类似于:

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 程序员新手。

【问题讨论】:

    标签: java sql postgresql postgis jooq


    【解决方案1】:

    使用 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&lt;YourType&gt; 而不是 Field&lt;?&gt; 以获得额外的类型安全性。

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2022-06-22
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 2010-12-24
      • 2018-02-28
      • 2010-11-01
      • 2019-03-07
      相关资源
      最近更新 更多