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;}
  • 属性筛选查询
    用数据库查:
    在这里插入图片描述
SELECT *FROM mzxm_lx WHERE xmbh = '3308812023104'  AND zzdybh = '3308812023104003' AND zzlx = '10'

在这里插入图片描述
用代码查:

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

在这里插入图片描述

  • 空间筛选
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("mzxm_lx", within);

如果不知道使用的什么关键字就比如相交INTERSECTS,可以点进对应的这个空间关系里去看这个Name,和这个保持一致。
在这里插入图片描述

总结:这里就在于怎么去写这个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);}}, "mzxm_lx" , geometry);SimpleFeatureType simpleFeatureType = dataStore.getSchema("mzxm_lx");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;}

在这里插入图片描述
图形也能正常展示:
在这里插入图片描述

/*** 通过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

在这里插入图片描述
所以下面这种方式是不会成功的,要成功的话必须设置所有的字段对应上,我懒得弄了原理就是上面源码那样的:

// 错误示范
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);
}}, "mzxm_lx" );
SimpleFeatureType simpleFeatureType = dataStore.getSchema("mzxm_lx");
pgTemplate.appendFeatureByFeatureWriter(simpleFeatureType, Arrays.asList(build));

更新

  • 更新属性
/*** 更新属性* @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("mzxm_lx");
pgTemplate.updateFeatures(simpleFeatureType, fieldsMap, CQL.toFilter(" xmbh = 'ceshiceshi'"));

在这里插入图片描述
如果你需要更新几何,只需要设置几何字段即可:

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);// 设置一个 FeatureReaderFeatureReader<SimpleFeatureType, SimpleFeature> featureReader = new CollectionFeatureReader(simpleFeature);featureStore.setFeatures(featureReader);featureReader.close();
}

这里还需要注意一点,featureReaders 是覆盖更新的逻辑,所以使用的时候要谨慎一点
在这里插入图片描述

下面有这么多实现类,具体怎么组合使用就看你的想象力了:
在这里插入图片描述

删除要素

/*** 删除数据** @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 代码难免写的比较草率,不要喷我奥,哈哈哈哈哈

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;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/338685.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据结构实验4:链表的基本操作

目录 一、实验目的 二、实验原理 1. 节点 2. 指针 3.链表的类型 3.1 单向链表 3.2 双向链表 3.3 单向循环链表 3.4 双向循环链表 4. 单链表的插入 4.1 头插法 4.2 尾插法 4.3 在指定位置插入元素 5. 单链表的删除 5.1 删除指定数值的节点 5.2 删除指定位置的节点 …

java基础之Java8新特性-Optional

目录 1.简介 2.Optional类常用方法 3.示例代码 4.示例代码仓库地址 1.简介 Java 8引入了一个重要的新特性&#xff0c;即Optional类。Optional类是为了解决空指针异常而设计的。 在Java中&#xff0c;当我们尝试访问一个空对象的属性或调用其方法时&#xff0c;很容易抛出…

如何创建自己的小程序?零编程一键创建实战指南

当今瞬息万变的数字世界中&#xff0c;拥有一个属于自己的小程序已成为企业与个人展示、服务和互动的重要途径。无需编码知识&#xff0c;通过便捷的云端可视化平台&#xff0c;也可以轻松创建一款符合自身需求且功能丰富的小程序。下面给大家分享如何创建自己的小程序。 1、选…

QT开发 2024最新版本优雅的使用vscode开发QT

▬▬▬▬▬▶VS开发QT◀▬▬▬▬▬ &#x1f384;先看效果 &#x1f384;编辑环境变量 如图添加环境变量&#xff01;&#xff01;&#xff01; 东西全在QT的安装目录&#xff01;&#xff01;&#xff01; 找到的按照我的教程再装一次&#xff01;&#xff01;&#xff01; 点…

OpenCV-21方盒滤波和均值滤波

一、方和滤波 使用API --- boxFiter(src, ddepth, ksize[,dst[,anchor[, normalize[, borderType]]]])方盒滤波 方盒滤波的卷积核如下所示&#xff1a; --- normalize Ture时&#xff0c; a 1 / &#xff08;W*H&#xff09;滤波器的宽高 --- normalize False时&#xff…

(超详细)YOLOV5改进-添加SimAM注意力机制

1、在yolov5/models下面新建一个SimAM.py文件&#xff0c;在里面放入下面的代码 代码如下&#xff1a; import torch import torch.nn as nnclass SimAM(torch.nn.Module):def __init__(self, e_lambda1e-4):super(SimAM, self).__init__()self.activaton nn.Sigmoid()self…

回归预测 | Matlab基于SO-LSTM蛇群算法优化长短期记忆神经网络的数据多输入单输出回归预测

回归预测 | Matlab基于SO-LSTM蛇群算法优化长短期记忆神经网络的数据多输入单输出回归预测 目录 回归预测 | Matlab基于SO-LSTM蛇群算法优化长短期记忆神经网络的数据多输入单输出回归预测效果一览基本介绍程序设计参考资料 效果一览 基本介绍 1.Matlab基于SO-LSTM蛇群算法优化…

鸿蒙HarmonyOS学习手册_入门篇

鸿蒙HarmonyOS学习手册_入门篇 文章目录 鸿蒙HarmonyOS学习手册_入门篇入门快速入门开发准备基本概念UI框架应用模型工具准备 构建第一个ArkTS应用&#xff08;Stage模型&#xff09;-快速入门-入门创建ArkTS工程ArkTS工程目录结构&#xff08;Stage模型&#xff09;构建第一个…

【NLP】多标签分类【上】

简介 《【NLP】多标签分类》主要介绍利用三种机器学习方法和一种序列生成方法来解决多标签分类问题&#xff08;包含实验与对应代码&#xff09;。共分为上下两篇&#xff0c;上篇聚焦三种机器学习方法&#xff0c;分别是&#xff1a;Binary Relevance (BR)、Classifier Chain…

基于YOLOv5+单目的物体距离和尺寸测量

目录 1&#xff0c;YOLOv5原理介绍 2,单目测尺寸以及距离原理 2.1单目测物体距离 2.2单目测物体尺寸 3&#xff0c;成果展示 3.3测距离 3.2测尺寸&#xff1a; 1&#xff0c;YOLOv5原理介绍 YOLOv5是目前应用广泛的目标检测算法之一&#xff0c;其主要结构分为两个部分&a…

算法与数据结构--最小生成树算法

一.应用的场景 类似于这种最小成本问题&#xff0c;实际上就是计算加权图把所有点连起来权重之和最小值的时候是怎么连接的。类似的问题还有最短耗时之类的问题。 二.最小生成树的定义 生成树&#xff1a; 图的生成树是它的一颗含有其所有顶点的无环连通子图。 【简单说就是所…

全志T113开发板Qt远程调试

1引言 通常情况下工程师在调试Qt程序时&#xff0c;需要频繁制作镜像烧录到核心板来测试Qt程序是否完善&#xff0c;这样的操作既费时又费力。这时我们可以通过QtCreator设备功能&#xff0c;定义设备后&#xff0c;在x86_64虚拟机上交叉编译qt程序&#xff0c;将程序远程部署到…