GROUP BY子句用于从一个或多个表中收集数据并将它们排列在一组中。在Criteria API中, AbstractQuery接口的groupBy()方法用于过滤记录并将其分组。
条件GROUP BY示例
【JPA条件 GROUP BY子句】在这里, 我们将对学生表执行GROUP BY操作。让我们假设该表包含以下记录:-
文章图片
现在, 请按照以下步骤执行操作:-
- 在com.srcmini.jpa包下创建一个实体类名称为StudentEntity.java。此类包含带有所有必需注释的三个属性s_id, s_name和s_age。
package com.srcmini.jpa;
import javax.persistence.*;
@Entity @Table(name="student") public class StudentEntity {@Idprivate int s_id;
private String s_name;
private int s_age;
public StudentEntity(int s_id, String s_name, int s_age) {super();
this.s_id = s_id;
this.s_name = s_name;
this.s_age = s_age;
}public StudentEntity() {super();
}public int getS_id() {return s_id;
}public void setS_id(int s_id) {this.s_id = s_id;
}public String getS_name() {return s_name;
}public void setS_name(String s_name) {this.s_name = s_name;
}public int getS_age() {return s_age;
}public void setS_age(int s_age) {this.s_age = s_age;
} }
- 现在, 在Persistence.xml文件中映射实体类和其他数据库配置。
<
persistence>
<
persistence-unit name="Student_details">
<
class>
com.srcmini.jpa.StudentEntity<
/class>
<
properties>
<
property name="javax.persistence.jdbc.driver" value="http://www.srcmini.com/com.mysql.jdbc.Driver"/>
<
property name="javax.persistence.jdbc.url" value="http://www.srcmini.com/jdbc:mysql://localhost:3306/studentdata"/>
<
property name="javax.persistence.jdbc.user" value="http://www.srcmini.com/root"/>
<
property name="javax.persistence.jdbc.password" value=""/>
<
property name="eclipselink.logging.level" value="http://www.srcmini.com/SEVERE"/>
<
property name="eclipselink.ddl-generation" value="http://www.srcmini.com/create-or-extend-tables"/>
<
/properties>
<
/persistence-unit>
<
/persistence>
- 一次, 我们创建了基本实体类并将配置映射到persistence.xml文件, 我们可以执行不同类型的GROUP BY操作。在这里, 我们根据年龄对学生人数进行分组。
package com.srcmini.jpa.jpql;
import com.srcmini.jpa.StudentEntity;
import javax.persistence.*;
import javax.persistence.criteria.*;
import java.util.*;
public class StudentGroup { public static void main( String args[]) {EntityManagerFactory emf = Persistence.createEntityManagerFactory( "Student_details" );
EntityManager em = emf.createEntityManager();
em.getTransaction().begin( );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<
Object[]>
cq = cb.createQuery(Object[].class);
Root<
StudentEntity>
stud = cq.from(StudentEntity.class);
cq.multiselect(stud.get("s_age"), cb.count(stud)).groupBy(stud.get("s_age"));
System.out.print("s_age");
System.out.println("\t Count");
List<
Object[]>
list = em.createQuery(cq).getResultList();
for(Object[] object : list){ System.out.println(object[0] + "" + object[1]);
}em.getTransaction().commit();
em.close();
emf.close();
}}
输出:
文章图片
推荐阅读
- JPA标准的Having子句
- PSD标准API
- JPA创建实体
- JPA集合映射
- JPA级联操作
- JPA级联删除
- JPA级联持久化
- Java毕业设计项目实战篇|Java项目:图书管理系统(java+SpringBoot+jpa+html+swagger+maven+mysql)