如何使用JPA 2中的示例对象获取数据

时间:2013-01-29 05:57:40

标签: hibernate jpa-2.0 criteria-api query-by-example

我正在使用Hibernate 3.5.6和JPA 2。

这是我的代码:

  public List<Route> searchRoutesEndingAt(GeoLocation destinationLocation,
        int destinationRangeInMeters, RouteUserPref routeUserPref) {
    Query query = entityManager.createNamedQuery("searchRoutesEndingAt");
    query.setParameter("lat1", destinationLocation.getLatitude());
    query.setParameter("lng1", destinationLocation.getLongitude());
    query.setParameter("destinationRangeInMeters", destinationRangeInMeters);
    try {
        return query.getResultList();
    } catch (NoResultException ex) {
        return null;
    }
}

在上面的代码中,我想根据具有各种属性的routeUserPref过滤结果集。

2 个答案:

答案 0 :(得分:0)

您可以使用Criteria API

尝试以下代码
Criteria criteria = session.createCriteria(RouteUserPref.class).add(routeUserPref);
return criteria.list();

答案 1 :(得分:0)

您将无法使用EntityManager afaik执行此操作,因为它未包含在标准中。

但是我认为所有供应商都会实现它,对你来说就像是:

休眠

使用Hibernate的Criteria API:

// get the native hibernate session
Session session = (Session) getEntityManager().getDelegate();
// create an example from our customer, exclude all zero valued numeric properties 
Example customerExample = Example.create(customer).excludeZeroes();
// create criteria based on the customer example
Criteria criteria = session.createCriteria(Customer.class).add(customerExample);
// perform the query
criteria.list();

取自:

JPA - FindByExample

顺便说一下他在openjpa中的例子是不完整的。如果你想要一个更好的版本,请在评论中给我。