【问题标题】:Hibernate Spatial - Query within an X kilometer radius?休眠空间 - 在 X 公里半径内查询?
【发布时间】:2013-11-30 07:51:51
【问题描述】:

我是 Hibernate Spatial 的新手,正在尝试对给定半径内的对象执行简单查询。我使用来自谷歌地图和其他来源的数据在我的数据库中创建了许多具有与纬度和经度相对应的属性的条目。这个属性在我的实体类中是这样定义的:

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

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

谁能告诉我有关如何构造这样的查询的任何信息?

【问题讨论】:

    标签: hibernate jpa geometry geospatial hibernate-spatial


    【解决方案1】:

    请参阅 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

    【讨论】:

    • 该页面上显示的示例显示了查询给定多边形内的点。我必须在查询中指定多边形吗?理想情况下,我可以给它一个点(纬度/经度)和一个半径,并在我的查询中使用它而不是多边形。如何使用 JTS/Hibernate Spatial 声明几何?
    • 嗯,圆是一种特殊的几何,但不是多边形。查看我更新的示例,了解如何创建圈子。
    • 好吧,这一切都说得通。我会试一试。但不幸的是,我遇到了这个错误 (stackoverflow.com/questions/20079825/…),在我解决它之前无法进行测试。
    • 我需要完全相同的东西...您如何确定半径是米/公里等单位??
    • 这个计算欧几里得距离,对于地球坐标的情况,不起作用
    猜你喜欢
    • 2015-10-18
    • 2013-04-26
    • 2022-08-15
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2020-07-20
    • 2011-03-13
    相关资源
    最近更新 更多