GeoTools之在MySQL数据库的上存储数据
最近接触到GeoTools这个工具,第一次做相关的java项目,过程很曲折。直接上代码,注释应该算详细,自己的一点理解,有不对的望指出。
public static void SaveData() throws IOException {
// 创建一个特征类型构造器
SimpleFeatureTypeBuilder featureTypeBuilder = new SimpleFeatureTypeBuilder();
// 设置名字。在创建了一个SimpleFeatureType schema后,可以通过schema.getTypeName得到。
featureTypeBuilder .setName("test");
// 添加属性
featureTypeBuilder.add("name", String.class);
featureTypeBuilder.add("size", Integer.class);
featureTypeBuilder.add("total", Double.class);
// 添加几何属性
// featureTypeBuilder.setCRS( DefaultGeographicCRS.WGS84 );
// 设置参考坐标系,感觉不设置也没有问题
featureTypeBuilder.add("the_geom", Polygon.class); // then add geometry
//以上的名字相当于数据库中的表名,添加的属性相当于数据库中的字段名
// 通过构造器来得到特征类型(或者说是特征结构)
SimpleFeatureType schema = featureTypeBuilder.buildFeatureType();
//与数据库连接,得到DataStore
DataStore dataStore=null;
//用schemaExit来判断是否数据库中已经存在这个表,如果存在就不必再创建表了(ds.createSchema(schema)就可以理解为创建表)
Boolean schemaExist=false;
try {
dataStore = DataStoreBuilder.buildDataStore();
for (String name : dataStore.getTypeNames()) {
if(name.equals(schema.getTypeName())){
schemaExist=true;
}
}
if(!schemaExist){
dataStore.createSchema(schema);
}
} catch (IOException e) {
e.printStackTrace();
}
//创建一个featureBuilder,用来创建feature
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(schema);
Coordinate[] coordinates=new Coordinate[]{new Coordinate(4, 0), new Coordinate(2, 2),
new Coordinate(4, 4), new Coordinate(6, 2), new Coordinate(4, 0)};
Polygon polygon=new GeometryFactory().createPolygon(coordinates);
featureBuilder.add("name");
featureBuilder.add(30);
featureBuilder.add(100);
featureBuilder.add(polygon);
SimpleFeature feature1 = featureBuilder.buildFeature(null);
List<SimpleFeature> listFeature=new ArrayList<SimpleFeature>();
listFeature.add(feature1);
System.out.println(schema.getTypeName());
//得到一个需要存储的对象(数据库中的某个表) 。DataStore(数据库)中的tableName(表名)
String tableName=schema.getTypeName();
SimpleFeatureStore store = (SimpleFeatureStore) dataStore.getFeatureSource(tableName);
SimpleFeatureCollection collection = new ListFeatureCollection(schema, listFeature);
Transaction transaction = new DefaultTransaction("save features");
store.setTransaction(transaction);
try {
store.addFeatures(collection);
transaction.commit();
transaction.close();
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
transaction.close();
}
}
转载自:https://blog.csdn.net/Handsome3618/article/details/86085170