Hibernate Spatial - 在 X 公里半径内查询?

标签 hibernate jpa geometry geospatial hibernate-spatial

我是 Hibernate Spatial 的新手,正在尝试对给定半径内的对象执行简单的查询。我使用 Google map 和其他来源的数据在数据库中创建了许多条目,其属性对应于纬度和经度。该属性在我的实体类中定义如下:

@Column
@Type(type = "org.hibernate.spatial.GeometryType")
private Point coordinates = null;

我现在正在尝试找出如何搜索坐标距给定点 x 公里半径内的所有实体对象。例如,我想查找落在该点 (12.34567,-76.54321) 50 公里半径范围内的对象。但是,我找不到任何示例或教程来解释如何在 Hibernate Spatial 中执行此操作。

任何人都可以给我有关如何构造这样的查询的任何信息吗?

最佳答案

参见 this resource 有关“空间查询”的教程,这是一种特殊的方言和 JTS library (开源)。

基本上,您执行以下操作(从引用的页面复制/粘贴):

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import util.JPAUtil;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.Date;
import java.util.List;

......

private List find(String wktFilter) {
    Geometry filter = wktToGeometry(wktFilter);
    EntityManager em = JPAUtil.createEntityManager();
    em.getTransaction().begin();
    Query query = em.createQuery("select e from Event e where within(e.location, :filter) = true", Event.class);
    query.setParameter("filter", filter);
    return query.getResultList();
}

private Geometry wktToGeometry(String wktPoint) {
    WKTReader fromText = new WKTReader();
    Geometry geom = null;
    try {
        geom = fromText.read(wktPoint);
    } catch (ParseException e) {
        throw new RuntimeException("Not a WKT string:" + wktPoint);
    }
    return geom;
}

要生成圆,请参阅 this resource (搜索“圆弧、圆和曲线”)。 再次从那里复制/粘贴:

//this method replaces the above wktToGeometry() method
private static Geometry createCircle(double x, double y, final double RADIUS) {
  GeometricShapeFactory shapeFactory = new GeometricShapeFactory();
  shapeFactory.setNumPoints(32);
  shapeFactory.setCentre(new Coordinate(x, y));//there are your coordinates
  shapeFactory.setSize(RADIUS * 2);//this is how you set the radius
  return shapeFactory.createCircle();
}

此外,您始终有解决方法,可以添加一些附加字段(使用 insertable=false, updatable=false 映射)以映射到 org.hibernate 使用的相同列.spatial.GeometryType,然后在查询中使用它们。要计算距离,请检查 euclidian distance formula .

关于Hibernate Spatial - 在 X 公里半径内查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20026177/

相关文章:

java - c3p0 中的关闭连接

c - 如果点在三角形内部(当点在三角形的边界上时有帮助)

hibernate - Spring JPA DTO 投影和处理具有空值的嵌套投影

java - 在 persistence.xml 中禁用 hibernate jpa 日志

java - 在 JPA 中注释包含非实体类的 Map

c++ - 用一个给定半径的圆覆盖最大点数的算法

用于将英国操作系统坐标从东/北转换为经度和纬度的 SQL 函数

java - 使用存储库的异步方法中的 Spring InvalidDataAccessApiUsageException

java - hbm2ddl 模式导出不会导致使用 Spring Security 创建实体

java - Hibernate 在调用 saveOrUpdate 时执行不需要的 SELECT