读取GeoJson文件并保存到PostgreSQL数据库


读取GeoJson文件并保存到PostgreSQL数据库

0. 准备工作

  • pom.xml
<repositories>
	<repository>
		<id>maven2-repository.dev.java.net</id>
		<name>Java.net repository</name>
		<url>http://download.java.net/maven/2</url>
	</repository>
	<repository>
		<id>osgeo</id>
		<name>Open Source Geospatial Foundation Repository</name>
		<url>http://download.osgeo.org/webdav/geotools/</url>
	</repository>
	<repository>
		<snapshots>
			<enabled>true</enabled>
		</snapshots>
		<id>boundless</id>
		<name>Boundless Maven Repository</name>
		<url>http://repo.boundlessgeo.com/main</url>
	</repository>
</repositories>

<dependencies>
	<dependency>
		<groupId>org.postgresql</groupId>
	    <artifactId>postgresql</artifactId>
	</dependency>
	<dependency>
	    <groupId>net.postgis</groupId>
	    <artifactId>postgis-jdbc</artifactId>
	    <version>2.2.1</version>
	</dependency>
	<dependency>
		<groupId>org.geotools</groupId>
		<artifactId>gt-shapefile</artifactId>
		<version>18.4</version>
	</dependency>
	
	<dependency>
		<groupId>org.geotools</groupId>
		<artifactId>gt-geojson</artifactId>
		<version>18.4</version>
	</dependency>
	<dependency>
	  	<groupId>com.alibaba</groupId>
	   <artifactId>fastjson</artifactId>
	   <version>1.2.47</version>
	</dependency>
</dependencies>

1. 代码部分

  • 实体对象封装
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @program: tool
 * @description:
 * @author: Mr.superbeyone
 * @create: 2018-10-16 12:12
 **/
public class ShapeModel implements Serializable {
   
	private static final long serialVersionUID = 1534826432673888264L;
	private String id;
    private String type;
    private List<Map<String,Object>> geometry;
    private List<Map<String,Object>> properties;
    //Get Set
}
  • Table
public class Table {
    private String name;                        // 表名称
    private List<Field> fields;                 // 字段信息
    private List<Index> indexs;                 // 索引信息
    private String remark;                      // 注释信息
    //Get Set
}
  • TableInfo
public class TableInfo {

    private Table table;
    private String tableName;
    private Long id;
    private String fieldString;
    private List<Object> filedValues;                     
    private List<String> query;                           //查询条件
    private Map<String, Object> filedValuesMap;           //字段对应
    private String updateString;                          //修改
	//Get  Set
}
  • 统一返回结果定义
/**
 * @program: tool
 * @description:
 * @author: Mr.superbeyone
 * @create: 2018-10-18 16:37
 **/
public class JsonResult<T> {

    private Integer code;

    private String msg;

    private T data;
    //Get Set
}
  • 构造插入语句
 /**
   * 
   * @param tableName 表名
   * @param file geojson文件
   * @return
   */
private JsonResult<String> saveGeoJsonFileData2DataBaseSql(String tableName, File file) {
        JsonResult<String> result = new JsonResult<>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            String line = "";
            String tmpLine = null;
            while ((tmpLine = br.readLine()) != null) {
                line += tmpLine;
                //line为原生json
            }


            JSONObject jsonObject = JSONObject.parseObject(line);
            JSONArray features = jsonObject.getJSONArray("features");
            if (features.size() < 0) {
                logger.info("geojson数据为空");
                result.setCode(ResultCodeEnum.SAVE_UPLOAD_FILE_DATA_SUCCESS.getCode());
                result.setMsg("geojson数据为空");
                return result;
            }


            TableInfo tableInfo;
            int tableResult = 0;

            for (int i = 0; i < features.size(); i++) {
                tableInfo = new TableInfo();
                final String[] fields = {""};


                JSONObject feature = features.getJSONObject(i);

                ShapeModel shapeModel = JSONObject.parseObject(feature.toJSONString(), ShapeModel.class);
                LinkedList<Object> linkedList = new LinkedList<>();
                fields[0] = "type,";
                linkedList.add(shapeModel.getType());
                GeometryJSON geometryJSON = new GeometryJSON();

                final StringReader[] reader = new StringReader[1];
                shapeModel.getGeometry().forEach((geometry) -> {
                    fields[0] += "geometry,";


                    ObjectMapper objectMapper = new ObjectMapper();
                    try {
                        String value = objectMapper.writeValueAsString(geometry);
                        reader[0] = new StringReader(value);
                        Geometry read = geometryJSON.read(reader[0]);
                        linkedList.add("st_geomfromtext(\'" + read + "\')");
                    } catch (Exception e) {
                        logger.error("插入Geojson文件出错:\t" + e);
                        result.setData("[GeoJson数据插入---失败]");
                        result.setCode(ResultCodeEnum.SAVE_UPLOAD_FILE_DATA_FAIL.getCode());
                        result.setMsg("GeoJson数据格式不符合官方规则");
                    }
                });
                shapeModel.getProperties().forEach((property) -> {
                    property.entrySet().forEach((entry) -> {
                        if (entry.getValue() != null) {
                            fields[0] += entry.getKey().toLowerCase() + ",";
                            linkedList.add(entry.getValue());
                        }
                    });

                });
                fields[0] += "createtime";
                linkedList.add(new Date());

                tableInfo.setFieldString(fields[0]);
                tableInfo.setFiledValues(linkedList);
                tableInfo.setTableName(tableName);
                //插入数据
                tableResult += tableInfoService.insertOne(tableInfo);

            }
            if (tableResult == features.size()) {
                logger.debug("[GeoJson数据插入---成功]");
                result.setCode(ResultCodeEnum.SAVE_UPLOAD_FILE_DATA_SUCCESS.getCode());
                result.setMsg(ResultCodeEnum.SAVE_UPLOAD_FILE_DATA_SUCCESS.getMsg());
            } else {
                logger.error("[GeoJson数据插入---失败]");
                result.setData("[GeoJson数据插入---失败]");
                result.setCode(ResultCodeEnum.SAVE_UPLOAD_FILE_DATA_FAIL.getCode());
                result.setMsg(ResultCodeEnum.SAVE_UPLOAD_FILE_DATA_FAIL.getMsg());
            }
        } catch (Exception e) {
            logger.error("[保存GeoJson文件数据到数据库出现异常:\t]" + e);
            result.setData("[保存GeoJson文件数据到数据库出现异常:\t]" + e);
            result.setCode(ResultCodeEnum.SAVE_UPLOAD_FILE_DATA_FAIL.getCode());
            result.setMsg(ResultCodeEnum.SAVE_UPLOAD_FILE_DATA_FAIL.getMsg());
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
  • TableInfoServiceImpl
@Service
public class TableInfoServiceImpl{
	@Autowired
	private TableInfoMapper tableInfoMapper;
//............省略若干方法
	public int insertOne(TableInfo tableInfo) {
		return tableInfoMapper.insertOne(tableInfo);
	}
}
  • insert语句片段
<insert id="insertOne"
		parameterType="com.tdt.cs.storage.pojo.TableInfo"
		useGeneratedKeys="true" keyProperty="id">
		INSERT INTO ${tableName} (${fieldString}) VALUES
		<foreach collection="filedValues" item="item" open="("
			close=")" separator=",">
			<choose>
				<when test="item.toString().contains('st_geomfromtext')">
					${item}
				</when>
				<otherwise>
					#{item}
				</otherwise>
			</choose>
		</foreach>
</insert>

转载自:https://blog.csdn.net/superbeyone/article/details/84747645

You may also like...