Geotools-PG空间库(Crud,属性查询,空间查询)

这篇具有很好参考价值的文章主要介绍了Geotools-PG空间库(Crud,属性查询,空间查询)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

建立连接

经过测试,这套连接逻辑除了支持纯PG以外,也支持人大金仓,凡是套壳PG的都可以尝试一下。我这里的测试环境是Geosence创建的pg SDE,数据库选用的是人大金仓。

/**
  * 获取数据库连接资源
  *
  * @param connectConfig
  * @return
  * {@link PostgisNGDataStoreFactory} PostgisNGDataStoreFactory还有跟多的定制化参数可以进去看看
  * @throws Exception
  */
 public static DataStore ConnectDatabase(GISConnectConfig connectConfig) throws Exception {
     if (pgDatastore != null) {
         return pgDatastore;
     }
     //数据库连接参数配置
     Map<String, Object> params = new HashMap<String, Object>();
     // 数据库类型
     params.put(PostgisNGDataStoreFactory.DBTYPE.key, connectConfig.getType());
     params.put(PostgisNGDataStoreFactory.HOST.key, connectConfig.getHost());
     params.put(PostgisNGDataStoreFactory.PORT.key, connectConfig.getPort());
     // 数据库名
     params.put(PostgisNGDataStoreFactory.DATABASE.key, connectConfig.getDataBase());
     //用户名和密码
     params.put(PostgisNGDataStoreFactory.USER.key, connectConfig.getUser());
     params.put(PostgisNGDataStoreFactory.PASSWD.key, connectConfig.getPassword());
     // 模式名称
     params.put(PostgisNGDataStoreFactory.SCHEMA.key, "sde");
     // 最大连接
     params.put( PostgisNGDataStoreFactory.MAXCONN.key, 25);
     // 最小连接
     params.put(PostgisNGDataStoreFactory.MINCONN.key, 10);
     // 超时时间
     params.put( PostgisNGDataStoreFactory.MAXWAIT.key, 10);
     try {
         pgDatastore = DataStoreFinder.getDataStore(params);
         return pgDatastore;
     } catch (IOException e) {
         LOG.error("获取数据源信息出错");
     }
     return null;
 }

查询

  • 查询所有的表格
/**
  * 查询所有的表格
  * @return
  * @throws IOException
  */
 public List<String> getAllTables() throws IOException {
     String[] typeNames = this.dataStore.getTypeNames();
     List<String> tables = Arrays.stream(typeNames).collect(Collectors.toList());
     return tables;
 }

属性查询&&空间查询通用

 /**
    * 查询要素
    * @param layerName
    * @param filter
    * @return
    * @throws IOException
    */
   public  SimpleFeatureCollection queryFeatures(String layerName, Filter filter) throws IOException {
       SimpleFeatureCollection features = null;
       try {
           SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName);
           features = featureSource.getFeatures(filter);
           return features;
       } catch (Exception e) {
           e.printStackTrace();
       }
       return features;
   }
  • 属性筛选查询
    用数据库查:
    Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑
SELECT *FROM demoWHERE xmbh = '3308812023104'  AND zzdybh = '3308812023104003' AND zzlx = '10'

Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑
用代码查:

 SimpleFeatureCollection simpleFeatureCollection = pgTemplate.queryFeatures("demo", CQL.toFilter("xmbh = '3308812023104'  AND zzdybh = '3308812023104003' AND zzlx = '10'"));

Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑

  • 空间筛选
Geometry geometry = new WKTReader().read("Polygon ((119.13571152004580256 29.96675730309299368, 119.14239751148502933 29.62242874397260195, 119.49341206204465493 29.84975245290645063, 119.23265839591465465 30.0670471746814556, 119.13571152004580256 29.96675730309299368))");
// 直接写SQL
Filter filter = CQL.toFilter("INTERSECTS(shape," + geometry .toString() + ")");
// 或者使用FilterFactory 
Within within = ff.within(ff.property("shape"), ff.literal(geometry));
SimpleFeatureCollection simpleFeatureCollection = pgTemplate.queryFeatures("demo", within);

如果不知道使用的什么关键字就比如相交INTERSECTS,可以点进对应的这个空间关系里去看这个Name,和这个保持一致。
Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑

总结:这里就在于怎么去写这个Filter,可以直接使用SQL语法。也可以自己去构造,需要借助这两个类

private static FilterFactory2 spatialFilterFc = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
private static FilterFactory propertyFilterFc = CommonFactoryFinder.getFilterFactory(null);

添加要素

/**
 * 
 * @param type 
 * @param features 需要追加的要素
 * @throws IOException
 */
public  void appendFeatures(SimpleFeatureType type, List<SimpleFeature> features) throws IOException {
    ListFeatureCollection featureCollection = new ListFeatureCollection(type, features);
    String typeName = type.getTypeName();
    FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(typeName);
    try {
        featureStore.addFeatures(featureCollection);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Transaction transaction = new DefaultTransaction("appendData");
    featureStore.setTransaction(transaction);
    transaction.commit();
}

测试代码:

Geometry geometry = new WKTReader().read("Polygon ((118.41044123299997182 29.89092741100000694, 118.42024576499994737 29.83296547499998042, 118.30907619399994246 29.75101510400003235, 118.19200671200002262 29.74673207400002184, 118.41044123299997182 29.89092741100000694))");
    SimpleFeature build = CustomFeatureBuilder.build(new HashMap<String, Object>() {{
        put("xmbh", "ceshiceshi");
        put("zxmmc", "测试一把");
        put("shape", geometry);
    }}, "demo" , geometry);
    SimpleFeatureType simpleFeatureType = dataStore.getSchema("demo");
    pgTemplate.appendFeatures(simpleFeatureType, Arrays.asList(build));

构建要素的代码如下:

/**
   *  构建一个Feature
   * @param fieldsMap
   * @param typeName
   * @return
   */
  public static SimpleFeature build(Map<String, Object> fieldsMap, String typeName) {
      SimpleFeatureTypeBuilder simpleFeatureTypeBuilder = new SimpleFeatureTypeBuilder();
      List<Object> values = new ArrayList<>();
      fieldsMap.forEach((key, val) -> {
          simpleFeatureTypeBuilder.add(key, val.getClass());
          values.add(val);
      });
      simpleFeatureTypeBuilder.setName(typeName);
      SimpleFeatureType simpleFeatureType = simpleFeatureTypeBuilder.buildFeatureType();
      SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeatureType);
      builder.addAll(values);
      SimpleFeature feature = builder.buildFeature(null);
      return feature;
  }

Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑
图形也能正常展示:
Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑

/**
  * 通过FeatureWriter 追加要素
  * @param type
  * @param features
  * @throws IOException
  */
 public  void appendFeatureByFeatureWriter(SimpleFeatureType type, List<SimpleFeature> features) throws IOException {
     String typeName = type.getTypeName();
     FeatureWriter<SimpleFeatureType, SimpleFeature> featureWriter = dataStore.getFeatureWriterAppend(typeName, new DefaultTransaction("appendData"));
     for (SimpleFeature feature : features) {
         SimpleFeature remoteNext = featureWriter.next();
         remoteNext.setAttributes(feature.getAttributes());
         remoteNext.setDefaultGeometry(feature.getDefaultGeometry());
         featureWriter.write();
     }
    featureWriter.close();
 }

使用FeatureWriter这个时候要注意啦,你插入的时候必须每个字段都设置值,追进源码里面发现它的SQL是写了所有字段的
源码路径:JDBCDataStore#insertNonPS

Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑
所以下面这种方式是不会成功的,要成功的话必须设置所有的字段对应上,我懒得弄了原理就是上面源码那样的:

// 错误示范 需要填所有字段
Geometry geometry = new WKTReader().read("Polygon ((118.41044123299997182 29.89092741100000694, 118.42024576499994737 29.83296547499998042, 118.30907619399994246 29.75101510400003235, 118.19200671200002262 29.74673207400002184, 118.41044123299997182 29.89092741100000694))");
SimpleFeature build = CustomFeatureBuilder.build(new HashMap<String, Object>() {{
    put("xmbh", "writer");
    put("zxmmc", "demo");
    put("zzdybh", "fdsa");
    put("shape", geometry);
}}, "demo" );
SimpleFeatureType simpleFeatureType = dataStore.getSchema("demo");
pgTemplate.appendFeatureByFeatureWriter(simpleFeatureType, Arrays.asList(build));

追加要素的原理都是借助于空间函数,我们如果调试源码就会发现最终生成了一个SQL类似于下面这个SQL

INSERT INTO "sde"."demo" ( "xmbh","zzdybh","zxmmc","zzlx","zxmlx","zxmbh","zgbm","jsgm","jhtz","xzgdmj","xzgddb","lxrq","wcrq","bz","txmj","bsm","czzj","shzj","gdb_geomattr_data","shape","objectid" ) VALUES ( 'ces','11111','update',null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,ST_GeomFromText('POLYGON ((119.1357115200458 29.966757303092994, 119.14239751148503 29.622428743972602, 119.49341206204465 29.84975245290645, 119.23265839591465 30.067047174681456, 119.1357115200458 29.966757303092994))', 4490),2)

源码如下:

{@link JDBCDataStore#insertNonPS}
try {
  for (SimpleFeature feature : features) {
      String sql = insertSQL(featureType, feature, keysFetcher, cx);

      ((BasicSQLDialect) dialect).onInsert(st, cx, featureType);

      LOGGER.log(Level.FINE, "Inserting new feature: {0}", sql);
      if (keysFetcher.hasAutoGeneratedKeys()) {
          st.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
      } else {
          st.executeUpdate(sql);
      }

      keysFetcher.postInsert(featureType, feature, cx, st);
  }
} finally {
  closeSafe(st);
}

更新

  • 更新属性
/**
   * 更新属性
   * @param type
   * @param fieldsMap
   * @param filter
   * @throws IOException
   */
  public  void updateFeatures(SimpleFeatureType type, Map<String, Object> fieldsMap, Filter filter) throws IOException {
      String typeName = type.getTypeName();
      List<Name> names =new ArrayList<>();
      FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(typeName);
      Set<String> keys = fieldsMap.keySet();
      for (String field : keys) {
          Name name = new NameImpl(field);
          names.add(name);
      }
      featureStore.modifyFeatures(names.toArray(new NameImpl[names.size()]), fieldsMap.values().toArray(), filter);
  }

测试代码:

HashMap<String, Object> fieldsMap = new HashMap<String, Object>() {{
    put("xmbh", "testupdate");
    put("zxmmc", "update");
    put("zzdybh", "3308812023104003");
}};
SimpleFeatureType simpleFeatureType = dataStore.getSchema("demo");
pgTemplate.updateFeatures(simpleFeatureType, fieldsMap, CQL.toFilter(" xmbh = 'ceshiceshi'"));

Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑
如果你需要更新几何,只需要设置几何字段即可:

HashMap<String, Object> fieldsMap = new HashMap<String, Object>() {{
     put("xmbh", "ces");
     put("zxmmc", "update");
     put("zzdybh", "3308812023104003");
     put("shape", geometry);
 }};

我们还可以这样写

/**
 * 覆盖更新
 * @param type
 * @param fieldsMap
 * @param filter
 * @throws IOException
 */
public  void updateFeatureFeatureReader(SimpleFeatureType type, Map<String, Object> fieldsMap, Filter filter) throws IOException {
    String typeName = type.getTypeName();
    FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(typeName);
    SimpleFeature simpleFeature = CustomFeatureBuilder.build(fieldsMap, typeName);
    // 设置一个 FeatureReader
    FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = new CollectionFeatureReader(simpleFeature);
    featureStore.setFeatures(featureReader);
    featureReader.close();
}

这里还需要注意一点,featureReaders 是覆盖更新的逻辑,所以使用的时候要谨慎一点
Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑

下面有这么多实现类,具体怎么组合使用就看你的想象力了:
Geotools-PG空间库(Crud,属性查询,空间查询),GIS,postgis,geotools,空间库,人大金仓,opengis,空间库编辑

删除要素

/**
 * 删除数据
 *
 * @param layerName 图层名称
 * @param filter 过滤器
 */
public  boolean deleteData(String layerName, Filter filter) {
    try {
        SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName);
        FeatureStore featureStore = (FeatureStore) featureSource;
        featureStore.removeFeatures(filter);
        Transaction transaction = new DefaultTransaction("delete");
        featureStore.setTransaction(transaction);
        transaction.commit();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

完整DEMO

Demo 代码难免写的比较草率,不要喷我奥,哈哈哈哈哈文章来源地址https://www.toymoban.com/news/detail-812401.html

public class PgTemplate {
private final DataStore dataStore;

public PgTemplate(DataStore dataStore) {
    this.dataStore = dataStore;
}

/**
 * @param type
 * @param features 需要追加的要素
 * @throws IOException
 */
public void appendFeatures(SimpleFeatureType type, List<SimpleFeature> features) throws IOException {
    ListFeatureCollection featureCollection = new ListFeatureCollection(type, features);
    String typeName = type.getTypeName();
    FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(typeName);
    try {
        featureStore.addFeatures(featureCollection);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Transaction transaction = new DefaultTransaction("appendData");
    featureStore.setTransaction(transaction);
    transaction.commit();
}

/**
 * 更新属性
 *
 * @param type
 * @param fieldsMap
 * @param filter
 * @throws IOException
 */
public void updateFeatures(SimpleFeatureType type, Map<String, Object> fieldsMap, Filter filter) throws IOException {
    String typeName = type.getTypeName();
    List<Name> names = new ArrayList<>();
    FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(typeName);
    Set<String> keys = fieldsMap.keySet();
    for (String field : keys) {
        Name name = new NameImpl(field);
        names.add(name);
    }
    featureStore.modifyFeatures(names.toArray(new NameImpl[names.size()]), fieldsMap.values().toArray(), filter);
}

/**
 * 覆盖更新
 *
 * @param type
 * @param fieldsMap
 * @param filter
 * @throws IOException
 */
public void updateFeatureFeatureReader(SimpleFeatureType type, Map<String, Object> fieldsMap, Filter filter) throws IOException {
    String typeName = type.getTypeName();
    FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(typeName);
    SimpleFeature simpleFeature = CustomFeatureBuilder.build(fieldsMap, typeName);
    FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = new CollectionFeatureReader(simpleFeature);
    featureStore.setFeatures(featureReader);
    featureReader.close();
}

/**
 * 通过FeatureWriter 追加要素
 *
 * @param type
 * @param features
 * @throws IOException
 */
public void appendFeatureByFeatureWriter(SimpleFeatureType type, List<SimpleFeature> features) throws IOException {
    String typeName = type.getTypeName();
    FeatureWriter<SimpleFeatureType, SimpleFeature> featureWriter = dataStore.getFeatureWriterAppend(typeName, new DefaultTransaction("appendData"));
    for (SimpleFeature feature : features) {
        SimpleFeature remoteNext = featureWriter.next();
        remoteNext.setAttributes(feature.getAttributes());
        remoteNext.setDefaultGeometry(feature.getDefaultGeometry());
        featureWriter.write();
    }
    featureWriter.close();
}

/**
 * 删除数据
 *
 * @param
 * @param
 * @param
 */
public boolean deleteData(String layerName, Filter filter) {
    try {
        SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName);
        FeatureStore featureStore = (FeatureStore) featureSource;
        featureStore.removeFeatures(filter);
        Transaction transaction = new DefaultTransaction("delete");
        featureStore.setTransaction(transaction);
        transaction.commit();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

/**
 * 查询要素
 *
 * @param layerName
 * @param filter
 * @return
 * @throws IOException
 */
public SimpleFeatureCollection queryFeatures(String layerName, Filter filter) throws IOException {
    SimpleFeatureCollection features = null;
    try {
        SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName);
        features = featureSource.getFeatures(filter);
        return features;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return features;
}

/**
 * 查询要素
 *
 * @param layerName
 * @param filter
 * @return
 * @throws IOException
 */
public SimpleFeatureCollection queryFeaturesByFeatureReader(String layerName, Filter filter) throws IOException {
    FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = dataStore.getFeatureReader(new Query(layerName, filter), new DefaultTransaction("query"));
    SimpleFeatureType featureType = featureReader.getFeatureType();
    List<SimpleFeature> features = new ArrayList<>();
    while (featureReader.hasNext()) {
        SimpleFeature next = featureReader.next();
        features.add(next);
    }
    return new ListFeatureCollection(featureType, features);
}

/**
 * 查询所有的表格
 *
 * @return
 * @throws IOException
 */
public List<String> getAllTables() throws IOException {
    String[] typeNames = this.dataStore.getTypeNames();
    List<String> tables = Arrays.stream(typeNames).collect(Collectors.toList());
    return tables;
}

到了这里,关于Geotools-PG空间库(Crud,属性查询,空间查询)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 一篇文章带你玩转PostGIS空间数据库

    1.什么是空间数据库 人类理解世界其实是按照三维的角度,而传统的关系型数据库是二维的,要想描述空间地理位置,点、线、面,我们就需要一个三维数据库,即所谓空间数据库。 postGIS就是一个空间数据库。 2.空间数据库是怎么存储的 除了普通数据库所具备的字符串、数

    2024年04月10日
    浏览(48)
  • 3 PostGIS基础查询

    使用命令登录数据库 psql -U postgres -d testdb -h localhost -p 5432 postgres用户名,testdb数据库名称,localhost ip地址,可以省略,5432端口,可以省略。 查看当前长时间执行却不结束的SQL 查出使用表扫描最多的表 查询读取buffer最多的5个SQL 获取数据库当前的回滚事务数以及死锁数 查询指

    2024年02月15日
    浏览(34)
  • Java一般用于postgis空间数据库通用的增删查改sql命令

    目录 1 增加 2 删除 3 查询 4 更新 \\\"public\\\".\\\"JGSQGW_Geo\\\"为某模式下得表  一般postgrel有这样的设计模式

    2024年02月13日
    浏览(46)
  • GIS空间分析之密度分析

    密度分析结果可以显示出点要素或线要素较为集中的地方。例如,每个城镇都可能有一个点值,这个点值表示该镇的人口总数,但是您想更多地了解人口随地区的分布情况。由于每个城镇内并非所有人都住在聚居点上,通过计算密度,您可以创建出一个显示整个地表上人口的

    2024年02月05日
    浏览(40)
  • 使用GIS空间分析进行植物生长区域选址

    经过观察可以发现某种珍贵植物在山区的某个区域位置生长状况明显要比其他区域好很多,通过研究了解到这种植物生长具有严格的生长条件。为了能更好地保护该种植物的生长环境,现在需要使用GIS空间分析方法,将适合植物生长的区域找出来。 树谷资料库资源大全(3月

    2023年04月09日
    浏览(74)
  • Avue-crud 常用方法、属性

    前言 Avue的v2版本是一个基于element-ui低代码前端框架,Avue的v3是一个基于element-plus低代码前端框架,它使用 JSON 配置来生成页面,可以减少页面开发工作量,极大提升效率。avue对于后台管理系统的开发极其便捷,就是配置不容易记住,熟练该框架配置来开发会好点,不然真不

    2024年02月01日
    浏览(39)
  • avue-crud属性配置项参数笔记分享

      Avue 是一个基于 Element-plus 低代码前端框架,它使用JSON 配置来生成页面,可以减少页面开发工作量,极大提升效率; 虽然Avue官网上面都有这些配置说明,但是如果刚开始接触不熟悉框架的话需要很久才找到自己需要的参数配置,为了方便自己今后查找使用,现将一些开发

    2024年02月13日
    浏览(33)
  • ​gp,pg常用数据类型,查询语句

    2024年02月15日
    浏览(37)
  • Pix4Dmapper空间三维模型的应用实例:GIS选址分析

      本文介绍基于 无人机影像建模完成后的结果 ,利用 ArcMap 软件进行 空间选址分析 ,从而实现空间三维模型应用的方法。 目录 1 空间分析目标确立 2 基于基本约束条件的选址求解 2.1 坡度计算与提取 2.2 海拔提取 2.3 LAS数据初探 2.4 淹没分析 2.5 区域相交 2.6 面积约束 3 基于

    2024年02月04日
    浏览(41)
  • python3连接pg库做SQL查询

    使用psycopg2连接在线数据库PostgreSQL数据库。 (1) 安装psycopg2 打开命令提示符或PowerShell,并输入以下命令来安装psycopg2-binary: (2) 连接代码示例,

    2024年02月11日
    浏览(43)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包