2016-03-07 79 views
0

生成謂語我需要創建一個謂語從表中讀取數據,其中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的數據?

回答

0

而不是max你必須使用greatest日期。最大爲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);