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

2024-01-11 02:04

本文主要是介绍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;
}

这篇关于Geotools-PG空间库(Crud,属性查询,空间查询)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/592784

相关文章

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

滚雪球学Java(87):Java事务处理:JDBC的ACID属性与实战技巧!真有两下子!

咦咦咦,各位小可爱,我是你们的好伙伴——bug菌,今天又来给大家普及Java SE啦,别躲起来啊,听我讲干货还不快点赞,赞多了我就有动力讲得更嗨啦!所以呀,养成先点赞后阅读的好习惯,别被干货淹没了哦~ 🏆本文收录于「滚雪球学Java」专栏,专业攻坚指数级提升,助你一臂之力,带你早日登顶🚀,欢迎大家关注&&收藏!持续更新中,up!up!up!! 环境说明:Windows 10

MySQL-CRUD入门1

文章目录 认识配置文件client节点mysql节点mysqld节点 数据的添加(Create)添加一行数据添加多行数据两种添加数据的效率对比 数据的查询(Retrieve)全列查询指定列查询查询中带有表达式关于字面量关于as重命名 临时表引入distinct去重order by 排序关于NULL 认识配置文件 在我们的MySQL服务安装好了之后, 会有一个配置文件, 也就

ural 1026. Questions and Answers 查询

1026. Questions and Answers Time limit: 2.0 second Memory limit: 64 MB Background The database of the Pentagon contains a top-secret information. We don’t know what the information is — you

Mybatis中的like查询

<if test="templateName != null and templateName != ''">AND template_name LIKE CONCAT('%',#{templateName,jdbcType=VARCHAR},'%')</if>

HTML5自定义属性对象Dataset

原文转自HTML5自定义属性对象Dataset简介 一、html5 自定义属性介绍 之前翻译的“你必须知道的28个HTML5特征、窍门和技术”一文中对于HTML5中自定义合法属性data-已经做过些介绍,就是在HTML5中我们可以使用data-前缀设置我们需要的自定义属性,来进行一些数据的存放,例如我们要在一个文字按钮上存放相对应的id: <a href="javascript:" d

京东物流查询|开发者调用API接口实现

快递聚合查询的优势 1、高效整合多种快递信息。2、实时动态更新。3、自动化管理流程。 聚合国内外1500家快递公司的物流信息查询服务,使用API接口查询京东物流的便捷步骤,首先选择专业的数据平台的快递API接口:物流快递查询API接口-单号查询API - 探数数据 以下示例是参考的示例代码: import requestsurl = "http://api.tanshuapi.com/a

【高等代数笔记】线性空间(一到四)

3. 线性空间 令 K n : = { ( a 1 , a 2 , . . . , a n ) ∣ a i ∈ K , i = 1 , 2 , . . . , n } \textbf{K}^{n}:=\{(a_{1},a_{2},...,a_{n})|a_{i}\in\textbf{K},i=1,2,...,n\} Kn:={(a1​,a2​,...,an​)∣ai​∈K,i=1,2,...,n

DAY16:什么是慢查询,导致的原因,优化方法 | undo log、redo log、binlog的用处 | MySQL有哪些锁

目录 什么是慢查询,导致的原因,优化方法 undo log、redo log、binlog的用处  MySQL有哪些锁   什么是慢查询,导致的原因,优化方法 数据库查询的执行时间超过指定的超时时间时,就被称为慢查询。 导致的原因: 查询语句比较复杂:查询涉及多个表,包含复杂的连接和子查询,可能导致执行时间较长。查询数据量大:当查询的数据量庞大时,即使查询本身并不复杂,也可能导致

Python中的属性装饰器:解锁更优雅的编程之道

引言 在Python的世界里,装饰器是一个强大的工具,它允许我们以一种非侵入性的方式修改函数或方法的行为。而当我们谈论“属性装饰器”时,则是在探讨如何使用装饰器来增强类中属性的功能。这不仅让我们的代码更加简洁、易读,同时也提供了强大的功能扩展能力。本文将带你深入了解属性装饰器的核心概念,并通过一系列实例展示其在不同场景下的应用,从基础到进阶,再到实际项目的实战经验分享,帮助你解锁Python编程