使用JPA Criteria Api和hibernate spatial 4

时间:2013-09-16 07:03:15

标签: java hibernate jpa criteria-api hibernate-spatial

在此处给出查询示例:http://www.hibernatespatial.org/tutorial-hs4.html

Query query = em.createQuery("select e from Event e where within(e.location, :filter) = true", Event.class);
query.setParameter("filter", filter);

是否可以使用jpa 2条件api重写查询?(我不确定如何处理within(e.location, :filter)部分。

3 个答案:

答案 0 :(得分:9)

我最近在完全相同的问题上工作。我的解决方案是内部关键字的谓词。

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

    public WithinPredicate(CriteriaBuilderImpl criteriaBuilder, Expression<Point> matchExpression, Geometry area) {
        this(criteriaBuilder, matchExpression, new LiteralExpression<Geometry>(criteriaBuilder, 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 ");
        return buffer.toString();
    }
}

您的查询将如下所示:

public List<Event> findEventInArea(Geometry area){
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Event> c = cb.createQuery(Event.class);

    Root<Event> event = c.from(Event.class);
    c.where(new WithinPredicate((CriteriaBuilderImpl) cb, event.get(Event_.location), area));
    Query query = entityManager.createQuery(c);
    return query.getResultList();
}

答案 1 :(得分:8)

JPA不支持空间。但是,您可以从JPA EntityManager中解包hibernate会话并运行空间条件。

此代码示例中的lat lon界限是任意的。

@PersistenceContext(unitName = "myPuName")
private EntityManager entityManager;

@Override
public List<City> findCities() {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Session session = entityManager.unwrap(Session.class);
    Criteria criteria = session.createCriteria(City.class);
    GeometryFactory geometryFactory = new GeometryFactory();
    Coordinate[] coordinates = {new Coordinate(-9,-9,0),new Coordinate(-9,9,0),new Coordinate(9,9,0),new Coordinate(9,-9,0),new Coordinate(-9,-9,0)};
    LinearRing polygon = geometryFactory.createLinearRing(coordinates);
    Polygon po = geometryFactory.createPolygon(polygon,null);
    criteria.add(SpatialRestrictions.within(City_.location.getName(), po));
    List list = criteria.list();
    return list;
}

以下是一些与该问题没有直接关系的代码。此类可用作要添加到休眠条件的“顺序”条件。它将按参数位置的距离对结果进行排序:

public class KnnOrder extends Order {
    private final Point fromPoint;

    public KnnOrder(String propertyName, boolean ascending, Point fromPoint) {
        super(propertyName, ascending);
        this.fromPoint = fromPoint;
    }

    @Override
    public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) {
        Dialect dialect = criteriaQuery.getFactory().getDialect();
        if (!dialect.getClass().isAssignableFrom(PostgisDialect.class)) {
            throw new UnsupportedOperationException("This supports only postgis dialect. Was requested: " + dialect.toString());
        }
//        final String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, super.getPropertyName());
//        String fromPointWkt = WKTWriter.toPoint(fromPoint.getCoordinate());
        return "location <-> st_setsrid(st_makepoint(" + fromPoint.getX() + "," + fromPoint.getY() + "),4326)";
    }
}

答案 2 :(得分:0)

在JPA2中,您可以使用函数表达式构建器。不再需要专用的东西。同样适用于订单表达。

~/.jitsi-meet-cfg/jibri

价格低廉:函数名称与数据库有关。在PostgreSQL中,内部函数称为st_within。