java - 在 JpaRepository 的查询中执行 PostGIS 函数

标签 java postgresql spring-data-jpa postgis

我有一个像这样的 JpaRepository:

public interface PipeRepository extends JpaRepository<Pipe, Long> {
    @Query("select p from Pipe p where st_intersects(p.geometry, ?1)=true")
    Collection<Pipe> find(Geometry envelope);

    @Query(value = "SELECT st_extent(p.geometry) FROM Pipe p WHERE p.id IN ?1")
    Geometry getPipe(Collection<Number> id);
}

第一个工作正常,但第二个在初始化期间抛出此异常:

org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode
\-[METHOD_CALL] MethodNode: '('
    +-[METHOD_NAME] IdentNode: 'st_extent' {originalText=st_extent}
    \-[EXPR_LIST] SqlNode: 'exprList'
       \-[DOT] DotNode: 'pipe0_.geometry' {propertyName=geometry,dereferenceType=PRIMITIVE,getPropertyPath=geometry,path=p.geometry,tableAlias=pipe0_,className=es.x.model.Pipe,classAlias=p}
          +-[ALIAS_REF] IdentNode: 'pipe0_.id' {alias=p, className=es.x.model.Pipe, tableAlias=pipe0_}
          \-[IDENT] IdentNode: 'geometry' {originalText=geometry}

有任何关于 st_intersects 有效而 st_extent 无效的原因吗?

更新:我认为问题在于 Spring Data JPA 无法识别 PostGIS 功能。这个聚合函数(SQL 的 sum)工作正常:

@Query("select sum(p.id) from Pipe p where p.id in ?1")
Number getPipesSum(Collection<Number> ids);

最佳答案

我也遇到过类似的问题,解决方法如下:

在 Spring Boot Repository 界面中,您可以使用 st_astext() 以 WKT 形式接收查询结果。

@Query(value = "SELECT st_astext(st_extent(p.geometry)) FROM Pipe p WHERE p.id IN ?1")
String getPipe(Collection<Number> id);

您将看到返回类型是 String (这可能是好的,也可能不是好的)。

从数据库中取回 WKT 后,我使用 org.locationtech.jts.geom.GeometryFactory 将其转换回几何图形

@Autowired
private GeometryFactory factory;

WKTReader reader = new WKTReader(factory);
Geometry geom = reader.read(yourReturnVariable);

如果您查看geom.getGeometryType(),您会发现它是一个可行的几何图形,您可以在其他操作中使用它。

正如我之前所说,这可能不是一个好的解决方案,但它确实有效

关于java - 在 JpaRepository 的查询中执行 PostGIS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40487881/

相关文章:

java - 从 JPanel 中删除多个 JComboBox

sql - Postgresql:从第二个表中选择的列的随机值

java - 在 Spring 存储库中获取可分页自定义查询的总行数

sql - 是否可以选择子查询

spring - 为什么以及何时在 Spring 中使用 @Inject 而不是 @Autowired?

spring - 无法找到 Spring Data JPA 的 Spring XML Schema 命名空间异常(仅在部署时!)

java - 如何让一个GAE服务器重复运行?

java - Android NullPointerException 蓝牙

java - R 中的 Apache POI

Postgresql:如何查询包含某些值的 JSONb 数组