我需要使用JPA Criteria API以格式
返回数据摘要“不同的价值” - >不同价值的数量
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createQuery(Tuple.class);
Root<User> root = criteriaQuery.from(User.class);
// this is where I want to get a count of the user levels and how many users per level
criteriaQuery.select(criteriaBuilder.tuple(
root.get(User_.userLevel),
// user count?
));
我更喜欢通过条件API执行此操作。
有人可以帮忙吗?
杰森
答案 0 :(得分:2)
这应该可以解决问题:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> tupleQuery = cb.createTupleQuery();
Root<User> root = tupleQuery.from( User.class );
tupleQuery
.select( cb.tuple( root.get( User_.userLevel ), cb.distinctCount( root ) ) )
.groupBy( root.get( User_.userLevel ) );
List<Tuple> results = entityManager.createQuery( tupleQuery ).getResultList();