Hibernate-Spatial + PostGIS中的谓词,用于在纬度/经度范围内在半径范围内搜索

时间:2016-09-12 11:16:52

标签: hibernate postgis predicate hibernate-spatial

我正在尝试在Hibernate-Spatial中使用Predicates在半径X英里(用户定义)内进行搜索。

虽然之前已经提出过这样的问题,但只有一次问过Predicates而且可能不是最新的,因为它不起作用。而且我必须能够使用谓词而不是HQL。

我通过另一个答案找到了如何为PostGIS的WITHIN关键字设置Predicate但是无法让查询运行。

在最后设置之后,我说明错误输出和包版本。

以下是我的架构中的内容:

CREATE EXTENSION Postgis;

CREATE TABLE "user" (
    id               bigint  NOT NULL,
    search_radius    int,
    latitude         double precision,
    longitude        double precision,
    location         geography(point, 4326),

    PRIMARY KEY (id)
);

在我的模特中:

import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.hibernate.annotations.Type;

@Entity
@Table(name = "`user`")
public class User implements UserDetails {
    @Id
    private Long id;
    private Integer searchRadius = 125;
    private Double latitude;
    private Double longitude;
    @Column(name = "location", columnDefinition = "geography(Point, 4326)", nullable = true)
    @Type(type = "jts_geometry")
    private Point location;

    ...

    private void updateLocation() {
        if (latitude != null && longitude != null) {
            try {
                location = (Point) new WKTReader().read("POINT(" + latitude + " " + longitude + ")");
                location.setSRID(Location.SRID);
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}

在lat / lng的setter中调用更新位置。

我从Using JPA Criteria Api and hibernate spatial 4 together

获得的谓词
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import java.io.Serializable;
import javax.persistence.criteria.Expression;
import org.hibernate.jpa.criteria.CriteriaBuilderImpl;
import org.hibernate.jpa.criteria.ParameterRegistry;
import org.hibernate.jpa.criteria.Renderable;
import org.hibernate.jpa.criteria.compile.RenderingContext;
import org.hibernate.jpa.criteria.predicate.AbstractSimplePredicate;

public class WithinPredicate extends AbstractSimplePredicate implements Expression<Boolean>, Serializable {
    private final Expression<Point> matchExpression;
    private final Expression<Geometry> area;

    public WithinPredicate(CriteriaBuilderImpl criteriaBuilder, Expression<Point> matchExpression, Expression<Geometry> area) {
        super(criteriaBuilder);
        this.matchExpression = matchExpression;
        this.area = area;
    }

    public Expression<Point> getMatchExpression() {
        return matchExpression;
    }

    public Expression<Geometry> getArea() {
        return area;
    }

    public void registerParameters(ParameterRegistry registry) {
        // Nothing to register
    }

    @Override
    public String render(boolean isNegated, RenderingContext renderingContext) {
        StringBuilder buffer = new StringBuilder();
        buffer.append(" within(")
            .append(((Renderable) getMatchExpression()).render(renderingContext))
            .append(", ")
            .append(((Renderable) getArea()).render(renderingContext))
            .append(" ) = true ");
        String bo = buffer.toString();

        return bo;
    }
}

使用WithinPredicate和circle factory创建查询。

import com.xxxx.repository.WithinPredicate;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.util.GeometricShapeFactory;

@Service
class ... {
    public List<User> fetchFor(User user) {
        ...
        Geometry radius = createCircle(user.getLatitude(), user.getLongitude(), user.getSearchRadius());
        radius.setSRID(Location.SRID);
        p = b.and(p, new WithinPredicate(
            (CriteriaBuilderImpl) b,
            u.get(User_.location),
            new LiteralExpression<Geometry>((CriteriaBuilderImpl) b, radius)
        ));
    }

    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().getBoundary();
    }
}

不幸的是,我输出的错误是:

2016-09-09 14:03:30.862  WARN 56393 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42883
2016-09-09 14:03:30.862 ERROR 56393 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: function st_within(geography, bytea) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 336

gradle中的Hibernate-spatial版本:

compile('org.hibernate:hibernate-spatial:5.0.9.Final')

我怀疑这个问题是由于模型/架构可能被设置为&#34; Geography(Point,4326)&#34;但是shapeFactory创建了一个类型半径&#34; Geometry(Point,4326)&#34;。

真的很感激任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

我只阅读了你的一部分问题,但是有些事情引发了一些危险信号:

  • 您需要将轴顺序翻转为(X Y)或(经度纬度)
  • ST_Within仅适用于geometry类型,不适用于geography
  • 要查找区域内的点,请不要创建不完美的缓冲点
  • geography类型会更快,更好地支持ST_DWithin;对于半径,只需将英里数转换为米数