I need to use the JPA Criteria API to return a summary from data in the format
"Distinct Value" -> Count of Distinct Value
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?
));
I prefer to do this via the criteria API.
Can anyone help?
Jason
This should do the trick:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.