我正在尝试使用 MyBatis 从 PostGIS 数据库查询数据,忽略地理空间数据。我在数据库中有下表:
CREATE TABLE salesgeometry
(
id bigint NOT NULL,
label character varying(255),
type character varying(255),
geom geometry,
CONSTRAINT salesgeometry_pkey PRIMARY KEY (id ),
CONSTRAINT enforce_dims_geom CHECK (st_ndims(geom) = 2),
CONSTRAINT enforce_srid_geom CHECK (st_srid(geom) = 4326)
)
我正在尝试使用此注释将其映射到 MyBatis:
@Select("SELECT id, type, label FROM salesgeometry WHERE ST_Within(" +
"ST_GeomFromText('POINT(#{longitude} #{latitude})', 4326), geom) " +
"AND type = #{type}")
Geometry getGeometryAtLocation(
@NotNull @Param("type") String geometryType,
@NotNull @Param("longitude") BigDecimal longitude,
@NotNull @Param("latitude") BigDecimal latitude
);
目标类有这样的字段:
public class Geometry {
private long id;
private String type;
private String label;
...
}
不幸的是这不起作用,相反我得到了一个
org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1.
如何只查询数据库中列的子集?
最佳答案
问题是 ST_GeomFromText('POINT(#{longitude} #{latitude})', 4326)
被 MyBatis 映射到准备好的语句,如下所示:ST_GeomFromText(' POINT(? ?)', 4326)
,它实际上不包含预期的参数,因为问号在引号内。
解决方案是使用字符串连接(如 ST_GeomFromText('POINT(' || #{longitude} || ' ' || #{latitude} || ')', 4326)
或使用字符串替换:ST_GeomFromText('POINT(${longitude} ${latitude})', 4326)
,它将值直接放入 SQL 语句中,而不是使用准备语句的参数。
以下映射有效(注意经度和纬度的两个美元符号):
@Select("SELECT id, type, label FROM salesgeometry WHERE ST_Within(" +
"ST_GeomFromText('POINT(${longitude} ${latitude})', 4326), geom) " +
"AND type = #{type}")
Geometry getGeometryAtLocation(
@NotNull @Param("type") String geometryType,
@NotNull @Param("longitude") BigDecimal longitude,
@NotNull @Param("latitude") BigDecimal latitude
);
关于java - 如何使用 MyBatis 从 PostGIS 查询列的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7777428/