使用条件查询

时间:2014-02-11 11:01:25

标签: java

如何使用条件

编写以下查询
StringBuilder queryString = new StringBuilder("from BorrowerEvaluationDTO b where b.hasEvaluation = TRUE"+" ");
                if(sector != null && !sector.trim().equals("")){
                    queryString.append (" AND b.sector = '" + sector + "'");
                }
queryString.append(" AND b.id in (select needProfile.id from Investment where investor.id = '"+investorId + "')");

1 个答案:

答案 0 :(得分:0)

我不确定你的模型是如何看起来的,但我认为你的查询或多或少会像这样:

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Object> criteria = cb.createQuery(Object.class);
        Root<Object> root = criteria.from(Object.class);
        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(cb.equal(root.get("hasEvaluation"), cb.literal(true)));

        if (sector != null && !sector.trim().equals("")) {
            predicates.add(cb.equal(root.get("hasEvaluation"),
                    cb.literal(sector)));

        }
        Subquery<Object> sub = criteria.subquery(Object.class);
        Root<Object> subRoot = sub.from(Object.class);
        sub.select(subRoot.get("needProfile").get("id"));
        sub.where(cb.equal(subRoot.get("investor").get("id"), investorId));
        predicates.add(root.get("needProfile").in(sub));

        criteria.where(predicates.toArray(new Predicate[predicates.size()]));