如何使用Java JDBC PreparedStatement占位符将GeoJSON多边形插入到PostGIS中?

时间:2016-04-16 13:22:58

标签: java jdbc leaflet postgis geojson

如果您正在使用javascript库“Leaflet”及其插件“Draw”,那么您可以检索geojson,如下所示:

{
    "type" : "Polygon",
    "coordinates" : [ [ [ 13.95938491821289, 53.41329518072117 ], [ 14.955865859985348, 54.412618223375205 ], [ 13.9606294631958, 54.4120067663998 ], [ 13.95938491821289, 53.41329518072117 ] ] ]
}

如果您将上述json发送到网络服务器(使用Java代码,例如Play Framework),我想知道 插入它或在postgis数据库中更新它而不使用的最简单方法 用于创建sql字符串的字符串连接。 实际上,它可以创建一个具有上述结构的SQL字符串,但是您希望避免字符串连接,这是我询问如何使用PreparedStatement占位符的原因。 例如,以下SQL代码可以直接从pgAdmin(以及通过JDBC代码)执行:

UPDATE polygons
SET 
    geom = ST_SetSRID(ST_GeomFromGeoJSON
    ('{
            "type" : "Polygon",
            "coordinates" : [ [ [ 13.95938491821289, 53.41329518072117 ], [ 14.955865859985348, 54.412618223375205 ], [ 13.9606294631958, 54.4120067663998 ], [ 13.95938491821289, 53.41329518072117 ] ] ]
    }'), 26918)  
WHERE polygonid = 1;

但是,正如大多数开发人员所了解的那样,我们应该避免使用字符串连接 使用占位符,例如,如果使用PreparedStatement(或者如果使用Spring Framework,则使用JdbcTemplate)。

下面是一些代码,用于说明哪些有效,哪些无效。

我正在使用的PostGIS数据库表是使用以下语句创建的:

CREATE TABLE polygons (
  polygonid serial NOT NULL,
  geom geometry(Polygon,26918),
  CONSTRAINT polygon_pkey PRIMARY KEY (polygonid)
);

在我的Maven文件pom.xml中,我正在使用此依赖项:

<dependency>
    <groupId>net.postgis</groupId>
    <artifactId>postgis-jdbc</artifactId>
    <version>2.2.0</version>
</dependency>

Java代码:

import java.sql.*;
import org.postgis.PGgeometry;
...
// For verbosity reasons, I am below not including 
// any try/catch/throw statements or any closings of connections/statements/recordsets

String url = "jdbc:postgresql://localhost:5432/nameOfYourDatabase";
Connection connection = DriverManager.getConnection(url, "postgres", "[YOUR_PASSWORD]");    

// First below is some SQL query code which works and thus 
// proves that the setup with jar files and database connection indeed works:    
long maxPolygonId  = 100L;
PreparedStatement ps = connection.prepareStatement(
    "SELECT polygonid , geom FROM polygons WHERE polygonid < ?"
);
ps.setLong(1, maxPolygonId);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
    long polygonId = rs.getLong(1);
    // Actually it works to use PGgeometry as below WITHOUT first having to do 
    // "((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry"));" 
    // as currently documented at http://postgis.net/docs/ch06.html#idp48666800
    PGgeometry geom = (PGgeometry)rs.getObject(2); 
    System.out.println("polygonId: " + polygonId);
    System.out.println("geom: " + geom); // e.g. "geom: SRID=26918;POLYGON((17.9661226272583 59.41375375704178, ... ,17.9661226272583 59.41375375704178))"
}        

// Below is some code that also indeed works fine but it uses string 
// concatenation for the json string instead of placeholder which I want to use instead   
String geoJson = 
    "   {   " +
    "       \"type\" : \"Polygon\",  " +
    "       \"coordinates\" : [ [ [ 13.95938491821289, 53.41329518072117 ], [ 14.955865859985348, 54.412618223375205 ], [ 13.9606294631958, 54.4120067663998 ], [ 13.95938491821289, 53.41329518072117 ] ] ]  " +
    "   }  ";                   
String sqlUpdatingWithGeoJson = 
        "  UPDATE polygons  " +
        "   SET  " +
        "       geom = ST_SetSRID(ST_GeomFromGeoJSON  " +
        "       ('  " +
                    geoJson + 
        "       '), 26918)  " +
        "   WHERE polygonid = ?  ";
long idForPolygonToUpdate = 1L;
ps = connection.prepareStatement(sqlUpdatingWithGeoJson);
ps.setLong(1, idForPolygonToUpdate);
ps.executeUpdate();

// Below is some code which does NOT work when I am trying 
// to use placeholder instead of string concatenation as above 
String sqlUpdatingWithGeoJsonAsPlaceHolder = 
        "  UPDATE polygons  " +
        "   SET  " +
        "       geom = ST_SetSRID(ST_GeomFromGeoJSON  " +
        "       ('  " +
                    " ? " + // NOTE that this line is the difference with the sql update string above ! 
        "       '), 26918)  " +
        "   WHERE polygonid = ?  ";         

ps = connection.prepareStatement(sqlUpdatingWithGeoJsonAsPlaceHolder);
ps.setString(1, geoJson);
ps.setLong(2, idForPolygonToUpdate);
// The above row results in the exception below
// org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1.            
ps.executeUpdate();               


// Below I instead tried  to replace the whole expression as a string to be set 
// through the placeholder but it does NOT work neither  
String geomValue =
        "       ST_SetSRID(ST_GeomFromGeoJSON  " +
        "       ('  " +
                    geoJson + 
        "       '), 26918)  ";          
String sqlUpdatingWithPostGisStatementForPlaceHolder = 
        "  UPDATE polygons  " +
        "   SET  " +
        "       geom = ?  " +
        "   WHERE polygonid = ?  ";
ps = connection.prepareStatement(sqlUpdatingWithPostGisStatementForPlaceHolder);
ps.setString(1, geomValue); // I have also tried setObject instead of setString here
ps.setLong(2, idForPolygonToUpdate);
// The above row also results in the same exception as previous above i.e. below exception:
// org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1.    
ps.executeUpdate();

也许解决方案可能是将json字符串转换为可以理解的Java对象 通过PostGIS / PostgreSQL JDBC驱动程序,然后使用方法“prepareStatement.setObject”, 但是那个Java对象应该使用什么类型,以及如何轻松地将json字符串转换为这样的对象?

1 个答案:

答案 0 :(得分:0)

String sqlUpdatingWithGeoJsonAsPlaceHolder = 
        "  UPDATE polygons  " +
        "   SET  " +
        "       geom = ST_SetSRID(ST_GeomFromGeoJSON(?), 26918)  " +
        "   WHERE polygonid = ?  ";         

ps = connection.prepareStatement(sqlUpdatingWithGeoJsonAsPlaceHolder);
ps.setString(1, geoJson);
ps.setLong(2, idForPolygonToUpdate);      
ps.executeUpdate();   

这个应该可以工作:你将geojson作为字符串传递。函数ST_GeomFromGeoJSON期望一个字符串作为第一个参数,因此可以准备和执行该语句。

您收到错误是因为您引用了问号。这样,问号不会被解释为占位符!