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

相关文章

Oracle查询优化之高效实现仅查询前10条记录的方法与实践

《Oracle查询优化之高效实现仅查询前10条记录的方法与实践》:本文主要介绍Oracle查询优化之高效实现仅查询前10条记录的相关资料,包括使用ROWNUM、ROW_NUMBER()函数、FET... 目录1. 使用 ROWNUM 查询2. 使用 ROW_NUMBER() 函数3. 使用 FETCH FI

数据库oracle用户密码过期查询及解决方案

《数据库oracle用户密码过期查询及解决方案》:本文主要介绍如何处理ORACLE数据库用户密码过期和修改密码期限的问题,包括创建用户、赋予权限、修改密码、解锁用户和设置密码期限,文中通过代码介绍... 目录前言一、创建用户、赋予权限、修改密码、解锁用户和设置期限二、查询用户密码期限和过期后的修改1.查询用

使用SQL语言查询多个Excel表格的操作方法

《使用SQL语言查询多个Excel表格的操作方法》本文介绍了如何使用SQL语言查询多个Excel表格,通过将所有Excel表格放入一个.xlsx文件中,并使用pandas和pandasql库进行读取和... 目录如何用SQL语言查询多个Excel表格如何使用sql查询excel内容1. 简介2. 实现思路3

Java如何通过反射机制获取数据类对象的属性及方法

《Java如何通过反射机制获取数据类对象的属性及方法》文章介绍了如何使用Java反射机制获取类对象的所有属性及其对应的get、set方法,以及如何通过反射机制实现类对象的实例化,感兴趣的朋友跟随小编一... 目录一、通过反射机制获取类对象的所有属性以及相应的get、set方法1.遍历类对象的所有属性2.获取

MySQL不使用子查询的原因及优化案例

《MySQL不使用子查询的原因及优化案例》对于mysql,不推荐使用子查询,效率太差,执行子查询时,MYSQL需要创建临时表,查询完毕后再删除这些临时表,所以,子查询的速度会受到一定的影响,本文给大家... 目录不推荐使用子查询和JOIN的原因解决方案优化案例案例1:查询所有有库存的商品信息案例2:使用EX

SpringBoot基于MyBatis-Plus实现Lambda Query查询的示例代码

《SpringBoot基于MyBatis-Plus实现LambdaQuery查询的示例代码》MyBatis-Plus是MyBatis的增强工具,简化了数据库操作,并提高了开发效率,它提供了多种查询方... 目录引言基础环境配置依赖配置(Maven)application.yml 配置表结构设计demo_st

Redis KEYS查询大批量数据替代方案

《RedisKEYS查询大批量数据替代方案》在使用Redis时,KEYS命令虽然简单直接,但其全表扫描的特性在处理大规模数据时会导致性能问题,甚至可能阻塞Redis服务,本文将介绍SCAN命令、有序... 目录前言KEYS命令问题背景替代方案1.使用 SCAN 命令2. 使用有序集合(Sorted Set)

vue如何监听对象或者数组某个属性的变化详解

《vue如何监听对象或者数组某个属性的变化详解》这篇文章主要给大家介绍了关于vue如何监听对象或者数组某个属性的变化,在Vue.js中可以通过watch监听属性变化并动态修改其他属性的值,watch通... 目录前言用watch监听深度监听使用计算属性watch和计算属性的区别在vue 3中使用watchE

MyBatis框架实现一个简单的数据查询操作

《MyBatis框架实现一个简单的数据查询操作》本文介绍了MyBatis框架下进行数据查询操作的详细步骤,括创建实体类、编写SQL标签、配置Mapper、开启驼峰命名映射以及执行SQL语句等,感兴趣的... 基于在前面几章我们已经学习了对MyBATis进行环境配置,并利用SqlSessionFactory核

PostgreSQL如何查询表结构和索引信息

《PostgreSQL如何查询表结构和索引信息》文章介绍了在PostgreSQL中查询表结构和索引信息的几种方法,包括使用`d`元命令、系统数据字典查询以及使用可视化工具DBeaver... 目录前言使用\d元命令查看表字段信息和索引信息通过系统数据字典查询表结构通过系统数据字典查询索引信息查询所有的表名可