[原创]java WEB学习笔记90:Hibernate学习之路-- -HQL检索方式,分页查询,命名查询语句,投影查询,报表查询

时间:2021-01-20 10:42:15

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Employee 
 package com.jason.hibernate.entities.HQL;

 public class Employee {

     private Integer id;
private String name;
private float salary;
private String email; private Department dept; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public float getSalary() {
return salary;
} public void setSalary(float salary) {
this.salary = salary;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Department getDept() {
return dept;
} public void setDept(Department dept) {
this.dept = dept;
} @Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" + salary
+ ", email=" + email + ", dept=" + dept + "]";
} }
Department 
 package com.jason.hibernate.entities.HQL;

 import java.util.HashSet;
import java.util.Set; public class Department { private Integer id;
private String name; private Set<Employee> emps = new HashSet<>(); public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Set<Employee> getEmps() {
return emps;
} public void setEmps(Set<Employee> emps) {
this.emps = emps;
} }

  Department.hbm.xml

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-10-6 19:46:22 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping package="com.jason.hibernate.entities.HQL"> <class name="Department" table="GG_DEPARTMENT"> <id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id> <property name="name" type="java.lang.String">
<column name="NAME" />
</property> <set name="emps" table="GG_EMPLOYEE" inverse="true" lazy="true">
<key>
<column name="DEPT_ID" />
</key>
<one-to-many class="Employee" />
</set> </class>
</hibernate-mapping>

Employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-10-6 19:46:22 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping package="com.jason.hibernate.entities.HQL"> <class name="Employee" table="GG_EMPLOYEE">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id> <property name="name" type="java.lang.String">
<column name="NAME" />
</property> <property name="salary" type="float">
<column name="SALARY" />
</property> <property name="email" type="java.lang.String">
<column name="EMAIL" />
</property> <many-to-one name="dept" class="Department" fetch="join">
<column name="DEPT_ID" />
</many-to-one> </class> </hibernate-mapping>

HibernateTest

 package com.jason.hibernate.entities.HQL;

 import java.util.List;

 import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class HibernateTest { private SessionFactory sessionFactory;
private Session session;
private Transaction transaction; // 创建上述三个对象
@Before
public void init() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); session = sessionFactory.openSession(); transaction = session.beginTransaction();
} // 关闭上述三个对象
@After
public void destroy() {
transaction.commit();
session.close();
sessionFactory.close();
} }

测试方法

1. 分页查询:

  1)setFirstResult(int firstResult): 设定从哪一个对象开始检索, 参数 firstResult 表示这个对象在查询结果中的索引位置, 索引位置的起始值为 0. 默认情况下, Query 从查询结果中的第一个对象开始检索  

  2)setMaxResults(int maxResults): 设定一次最多检索出的对象的数目. 在默认情况下, Query 和 Criteria 接口检索出查询结果中所有的对象

 @Test
public void testPageQuery(){
String hql = "FROM Employee";
Query query = session.createQuery(hql); int pageNo = 3;
int pageSize = 5; List<Employee> emps =query.setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).list(); for(Employee emp : emps){
System.out.println(emp); } }

[原创]java WEB学习笔记90:Hibernate学习之路-- -HQL检索方式,分页查询,命名查询语句,投影查询,报表查询

2.命名查询语句

  1)Hibernate 允许在映射文件中定义字符串形式的查询语句

  2)<query> 元素用于定义一个 HQL 查询语句, 它和 <class> 元素并列.

  3)在程序中通过 Session 的 getNamedQuery() 方法获取查询语句对应的 Query 对象.

在employee.hbm.xml 中添加如下命名

 <!-- 命名查询 -->
<query name="salaryEmps"><![CDATA[FROM Employee e WHERE e.salary > :minSal AND e.salary < :maxSal]]> </query>

测试

 @Test
public void testNamedQuery(){ Query query = session.getNamedQuery("salaryEmps");
List<Employee> emps = query.setFloat("minSal", 5000).setFloat("maxSal", 10000).list();
System.out.println(emps.size()); }

  [原创]java WEB学习笔记90:Hibernate学习之路-- -HQL检索方式,分页查询,命名查询语句,投影查询,报表查询

3.投影查询

  1)投影查询: 查询结果仅包含实体的部分属性. 通过 SELECT 关键字实现.

  2)Query 的 list() 方法返回的集合中包含的是数组类型的元素, 每个对象数组代表查询结果的一条记录

  3)可以在持久化类中定义一个对象的构造器来包装投影查询返回的记录, 使程序代码能完全运用面向对象的语义来访问查询结果集.

  4)可以通过 DISTINCT 关键字来保证查询结果不会返回重复元素

方式一:

 @Test
public void testFieldQuery(){ String hql = "SELECT e.email, e.salary FROM Employee e WHERE e.dept = :dept";
Query query = session.createQuery(hql); Department dept = new Department();
dept.setId(80);
List<Object[]> result = query.setEntity("dept", dept).list();

for(Object[] objs : result){
System.out.println(Arrays.asList(objs));
} }

[原创]java WEB学习笔记90:Hibernate学习之路-- -HQL检索方式,分页查询,命名查询语句,投影查询,报表查询

方式二:推荐

  ① 将返回的属性,在持久化类中封装返回属性的构造器,按照属性定义的顺序

  ② 结果返回给 一个list<entity> 的集合

  ③ 通过遍历集合,输出值

测试方法

 @Test
public void testFieldQuery(){ String hql = "SELECT new Employee(e.email, e.salary, e.dept) FROM Employee e WHERE e.dept = :dept";
Query query = session.createQuery(hql); Department dept = new Department();
dept.setId(80);
List<Employee> result = query.setEntity("dept", dept).list();

for(Employee emp : result){
System.out.println(emp.getId() + "," + emp.getEmail() + "," + emp.getSalary() + "," + emp.getDept());
} }

  在Employee 持久化类中增加一个特定的构造器

 public Employee(String email, float salary,  Department dept) {
super();
this.salary = salary;
this.email = email;
this.dept = dept;
}

4.报表查询:

  1)报表查询用于对数据分组和统计, 与 SQL 一样, HQL 利用 GROUP BY 关键字对数据分组, 用 HAVING 关键字对分组数据设定约束条件.

  2)在 HQL 查询语句中可以调用以下聚集函数:count() min() max() sum() avg()

 @Test
public void testGroupBy(){ String hql = "SELECT min(e.salary) , max(e.salary)"
+ "FROM Employee e "
+ "GROUP BY e.dept "
+ "HAVING min(e.salary) > :minSal"; Query query = session.createQuery(hql).setFloat("minSal", 5000);
List<Object[]> result = query.list();
for(Object[] objs : result){
System.out.println(Arrays.asList(objs));
} }

[原创]java WEB学习笔记90:Hibernate学习之路-- -HQL检索方式,分页查询,命名查询语句,投影查询,报表查询