在JPA中可以通过建立投影(SELECT)查询使用聚合函数。步骤如下:
- 使用投影查询语法SELECT,选择实体的属性和聚合函数。
- 通过创建Query或TypedQuery执行查询。
- 调用getSingleResult()或getResultList()方法获取结果。
代码示例:
COUNT聚合函数:
String jpql = "SELECT COUNT(u) FROM User u";
Query query = em.createQuery(jpql);
Long count = (Long) query.getSingleResult();
SUM、AVG、MAX、MIN聚合函数:
String jpql = "SELECT SUM(u.age), AVG(u.age), MAX(u.age), MIN(u.age) FROM User u";
Query query = em.createQuery(jpql);
Object[] results = (Object[]) query.getSingleResult();
long sum = (Long) results[0];
double avg = (Double) results[1];
int max = (Integer) results[2];
int min = (Integer) results[3];
GROUP BY与HAVING语句:
String jpql = "SELECT u.department, COUNT(u) " +
"FROM User u GROUP BY u.department HAVING COUNT(u) > 10";
Query query = em.createQuery(jpql);
List<Object[]> results = query.getResultList();