问题描述
在这里给出查询示例:
Given the query example here: 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重写查询?(我不确定我该如何处理与在(e.location,:filter)
部分中。
Is it possible to rewrite the query using jpa 2 criteria api?( I am unsure how i should deal with the within(e.location, :filter)
part.
推荐答案
JPA不支持空间,但是,您可以从JPA EntityManager中解开hibernate会话并运行空间标准。
JPA does not support spatial. However, you can unwrap the hibernate session from your JPA EntityManager and run spatial criteria.
此代码示例中的纬度边界是任意的。
The lat lon bounds in this code sample is arbitrary.
@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;
}
以下是一些与问题没有直接关系的代码。这个类可以用作添加到休眠条件的Order条件。它将按照距参数位置的距离排序结果:
Here is some more code not directly related to the question. This class can be used as an "Order" criteria to be added to a hibernate criteria. It will sort results by distance from the argument location:
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)";
}
}
这篇关于一起使用JPA Criteria Api和hibernate spatial 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!