【问题标题】:How to fetch data using example object in JPA 2如何使用 JPA 2 中的示例对象获取数据
【发布时间】:2013-01-29 05:57:40
【问题描述】:

我正在使用 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 过滤结果集。

【问题讨论】:

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


    【解决方案1】:

    您可以使用 Criteria API 尝试以下代码

    Criteria criteria = session.createCriteria(RouteUserPref.class).add(routeUserPref);
    return criteria.list();
    

    【讨论】:

    • 我正在使用实体管理器,我无法直接访问休眠会话。所以这行不通。
    【解决方案2】:

    您将无法使用 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 中的例子是不完整的。如果您想要更好的版本,请在评论中联系我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 2018-08-30
      • 2018-05-04
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 2014-09-27
      相关资源
      最近更新 更多