0

I want to select three attributes from users table, but it returns all the attributes of users.The following code I used:


Specification<Users> spec = new Specification<Users>() {

            @Override
            public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query,
                    CriteriaBuilder cb) {
                // TODO Auto-generated method stub
                List<Predicate> ps = new ArrayList<Predicate>();
                ps.add(cb.equal(root.<String>get("userName"), userName));

                List<Selection<?>> selections = new ArrayList<Selection<?>>();
                selections.add(root.get("id"));
                selections.add(root.get("birth"));
                selections.add(root.get("userName"));
                query.multiselect(selections);

                query.where(ps.toArray(new Predicate[ps.size()]));
                return query.getRestriction();
            }
        };
        return repository.findOne(spec);

I am waiting for your advice.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lee Eric
  • 11
  • 2

2 Answers2

1

I have encountered such problems, multiselect also does not work, for another way OK:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();           
    CriteriaQuery<Tuple> cq = cb.createTupleQuery();     
    Root<AccountFlowInfoEntity> root = cq.from(AccountFlowInfoEntity.class);

    List<Expression<?>> grouping = new ArrayList<Expression<?>>();
    grouping.add(root.get("tradeDate"));
    grouping.add(root.get("tradeType"));
    cq.multiselect(root.get("tradeDate"),
                   root.get("tradeType"),
                   cb.sum(root<BigDecimal> get("tradeAmount"))
                   );

    Predicate p = cb.conjunction();
    if (!StringUtils.isEmpty(root.get("custId")))
    p=cb.and(p,cb.equal(root<String>get("custId"),paramsMap.get("custId")));

    cq.where(p);
    cq.groupBy(grouping).orderBy(cb.asc(root.get("id")));
    Query query  = entityManager.createQuery(cq).
 setFirstResult((int)paramsMap.get("pageNum")).setMaxResults((int)paramsMap.get("pageSize"));
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Due to known issue https://jira.spring.io/browse/DATAJPA-1532 Multiselect does not work with repo.findall method. I handled this by autowiring entity manager to service class. You can find working code here https://github.com/bsridharpatnaik/CriteriaMultiselectGroupBy

Sridhar Patnaik
  • 970
  • 1
  • 13
  • 24