【问题标题】:Generating predicate for latest date value为最新日期值生成谓词
【发布时间】:2016-06-20 21:07:54
【问题描述】:

我需要创建一个谓词来从regId = ? (||) or (&&) estCode = ? && latest (referralEntryDate) 所在的表中获取数据

获取最新日期的数据

@Override
public Predicate toPredicate(Root<ReviewMedicalStatus> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

    List<Predicate> predicatesReg = new ArrayList<Predicate>();

    if (revStatusDto.getRegId() != null && !StringUtils.isEmpty(revStatusDto.getRegId())) {
        predicatesReg.add(cb.equal(root.get("regId"), revStatusDto.getRegId()));
    }
    if (revStatusDto.getEstCode() != null && !StringUtils.isEmpty(revStatusDto.getEstCode())) {
        predicatesReg.add(cb.equal(root.get("estCode"), revStatusDto.getEstCode()));
    }

    Expression maxExpression = cb.max(root.get("referralEntryDate"));
    predicatesReg.add(maxExpression);
    //predicatesReg.add(cb.max(root.get("referralEntryDate")));
    return cb.and(predicatesReg.toArray(new Predicate[predicatesReg.size()]));
}

这是失败的,因为表达式不能作为参数传递给谓词。如何获取最新的referralEntryDate 的数据?

【问题讨论】:

    标签: spring jpa predicate criteria-api


    【解决方案1】:

    您必须使用greatest 代替max 日期。 Max 用于Numeric 类型。为了将它放在谓词中,您需要从中创建一个子查询。参考:JPA Criteria select all instances with max values in their groups。这不完全是你的实体集,但它应该给你的想法:

    CriteriaBuilder cb = em.getCriteriaBuilder();
    // make main query for Content
    CriteriaQuery<Content> q = cb.createQuery(Content.class);
    Root<Content> c = q.from(Content.class);
    
    // make subquery for date
    Subquery<Date> sq = q.subquery(Date.class);
    Root<Content> c2 = sq.from(Content.class);
    
    // get the max date in the subquery
    sq.select(cb.greatest(c2.<Date>get("date")));
    
    // make a predicate out of the subquery
    Predicate p = cb.equal(c.get("date"), sq);
    
    // assign predicate to the main query
    q.where(p);        
    
    // and get the results
    Content r = em.createQuery(q).getSingleResult();
    System.out.println(r);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多