在使用postgresql 9.3
postgis 2.1
的web项目上工作。
表中有一个类型为geography
的列,它只存储一个point
。
现在,我需要使用Java对象通过JDBC插入/选择类型。
在阅读了postgis
手册之后,没有发现太多相关的信息。
的问题是:
mybatis
,那么它会对上述问题的答案产生影响吗?发布于 2015-04-21 03:55:20
发布于 2017-09-20 07:07:19
如果使用MyBatis,MyBatis中有一个用于Postgis类型的小项目。并且它已经添加到maven central中,因此您可以直接从maven使用它。
发布于 2017-02-08 09:49:04
如果您正在使用TypeHandler,则可以透明地进行纬度和经度之间的转换。下面是我是如何在一个场景中这样做的,比如你的,PostGIS,Mybatis,和地理需要。使用TypeHandler可以处理不同的类,您可以将几何类型打包到其中。在我的例子中,坐标有两个double
属性,latitude
和longitude
。
坐标类
public class Coordinate {
private Double latitude;
private Double latitude;
... getters, setters, etc
}
声明Ibati的TypeHandler
@MappedJdbcTypes(JdbcType.JAVA_OBJECT)
@MappedTypes({Coordinate.class})
public class CoordinateTypeHandler extends BaseTypeHandler<Coordinate> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Coordinate parameter, JdbcType jdbcType) throws SQLException {
// Convert Coordinate to Ibatis representation of Postgis point, e.g., "SRID=4326;POINT(2.294801 48.858007)"
Point point = new Point(parameter.getLongitude(), parameter.getLatitude());
point.setSrid(4326);
ps.setString(i, point.toString());
}
// Convert data read from Ibatis to actual Coordinate class
@Override
public Coordinate getNullableResult(ResultSet rs, String columnName) throws SQLException {
return from(rs.getString(columnName));
}
@Override
public Coordinate getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return from(rs.getString(columnIndex));
}
@Override
public Coordinate getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return from(cs.getString(columnIndex));
}
protected Coordinate from(String pointAsText) throws SQLException {
if (pointAsText != null) {
Point point = new Point(pointAsText);
return new Coordinate(point.getY(), point.getX());
}
return null;
}
}
然后,准备你的选择在伊巴提斯的界面。参考这里的用法'as coordinate'
,它告诉Ibatis查找坐标类型的表示,这是您刚才定义的CoordinateTypeHandler
处理的。
重要的是要知道,在您的表定义中,location
bellow被声明为location geography(POINT, 4326)
。
@Select("SELECT " +
"ST_AsText(location) AS coordinate" +
"FROM " +
"mytable " +
"WHERE " +
"tableattribute = #{myattribute}")
List<Result> myFindMethod(
@Param("myattribute") Integer myattribute
);
该解决方案将为坐标类提供一个干净的抽象,该类将latitude
和longitude
属性封装到PostGIS上的SRID=4326;POINT(2.294801 48.858007)
表示。考虑到Mike的解决方案,您需要为要在API/服务上创建的每个查询重写相同的(ST_SetSRID(ST_MakePoint(:lon, :lat), 4326)::geography)
。
使用TypeHandler
的目的是避免这种情况,一旦您更改/添加了您的TypeHandler
的表示,它将直接反映在您使用as coordinate
的每个查询上。
https://stackoverflow.com/questions/29744816
复制相似问题