postGis有这样一张表test:字段id,空间数据geom,time字段。现在需要前端输入时间参数,后端按这个参数查询数据库数据,将查询到的数据导出为一份shp文件。现在我使用语句 select id,ST_AsText(geom) as wkt,time from test where time='2023 04-25 00:00'查出需要的结果,请给出一份完整的代码示例,使用springboot框架,给出包含实体类、mapper层、service、serviceImpl、controller的所有代码 可以使用geotools或gdal
时间: 2024-02-22 17:00:58 浏览: 112
PostGis数据介绍技术+空间数据处理、查询、管理技术简单讲解
以下是使用 GeoTools 的完整代码示例,包含实体类、mapper 层、service、serviceImpl、controller 的所有代码。
1. 实体类
```java
import org.locationtech.jts.geom.Geometry;
public class TestEntity {
private Long id;
private Geometry geom;
private String time;
// getter 和 setter 略
}
```
2. Mapper 层
```java
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.locationtech.jts.geom.Geometry;
import java.util.List;
@Mapper
public interface TestMapper {
@Select("SELECT id, geom, time FROM test WHERE time = #{time}")
List<TestEntity> findByTime(@Param("time") String time);
@Select("SELECT ST_AsText(geom) FROM test WHERE id = #{id}")
String findWktById(@Param("id") Long id);
}
```
3. Service
```java
import java.util.List;
public interface TestService {
List<TestEntity> findByTime(String time);
byte[] exportToShp(List<TestEntity> entities);
}
```
4. ServiceImpl
```java
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Autowired
private DataSource dataSource;
@Override
public List<TestEntity> findByTime(String time) {
return testMapper.findByTime(time);
}
@Override
@Transactional(readOnly = true)
public byte[] exportToShp(List<TestEntity> entities) {
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Object> params = new HashMap<>();
params.put("url", getTempFileUrl());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore dataStore;
try {
dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
} catch (IOException e) {
throw new RuntimeException("创建 ShapefileDataStore 失败", e);
}
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
typeBuilder.setName("TestEntity");
typeBuilder.setCRS(org.geotools.referencing.crs.DefaultGeographicCRS.WGS84);
typeBuilder.add("geom", Geometry.class);
typeBuilder.add("id", Long.class);
typeBuilder.add("time", String.class);
SimpleFeatureType featureType = typeBuilder.buildFeatureType();
try {
dataStore.createSchema(featureType);
} catch (IOException e) {
throw new RuntimeException("创建 Schema 失败", e);
}
Transaction transaction = new DefaultTransaction("create");
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource;
try {
featureSource = dataStore.getFeatureSource(typeName);
} catch (IOException e) {
throw new RuntimeException("获取 FeatureSource 失败", e);
}
List<SimpleFeature> features = new ArrayList<>();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
for (TestEntity entity : entities) {
Geometry geometry = entity.getGeom();
Long id = entity.getId();
String time = entity.getTime();
SimpleFeature feature = featureBuilder.buildFeature(null);
feature.setDefaultGeometry(geometry);
feature.setAttribute("id", id);
feature.setAttribute("time", time);
features.add(feature);
}
try {
SimpleFeatureCollection featureCollection = new ListFeatureCollection(featureType, features);
featureSource.addFeatures(featureCollection);
transaction.commit();
} catch (IOException e) {
throw new RuntimeException("添加 Feature 失败", e);
} finally {
try {
transaction.close();
} catch (IOException e) {
throw new RuntimeException("关闭 Transaction 失败", e);
}
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
org.geotools.data.DataUtilities.encodeFeatureCollection(featureSource.getFeatures(), outputStream);
} catch (IOException e) {
throw new RuntimeException("编码 FeatureCollection 失败", e);
}
return outputStream.toByteArray();
}
private String getTempFileUrl() {
try {
return "file://" + java.nio.file.Files.createTempFile("temp", ".shp").toAbsolutePath();
} catch (IOException e) {
throw new RuntimeException("创建临时文件失败", e);
}
}
}
```
5. Controller
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
@RestController
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/export")
public ResponseEntity<byte[]> export(@RequestParam String time) {
List<TestEntity> entities = testService.findByTime(time);
byte[] shpBytes = testService.exportToShp(entities);
String filename = "test_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".zip";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", filename, StandardCharsets.UTF_8);
return ResponseEntity.ok().headers(headers).body(shpBytes);
}
}
```
希望这份代码对你有所帮助!
阅读全文