---
title: "hibernate开发4--hibernate常用检索方式归纳"
author: "舟舟同学"
date: "2016-05-19T18:14:46Z"
tags: ["Hibernate"]
categories: ["编程语言"]
slug: "hibernate-4-hibernate"
draft: false
lastmod: "2016-05-19T18:15:47Z"
id: 2299319
url: "https://673390302.iteye.com/blog/2299319"
---

这里总结了hibernate常用的一些检索方式，供大家参考。

1、多态查询

在HQL中，如果查询一个表中的所有记录，语句如下：

String  queryString="from cat";

或者指定其包名，例如cat的包名为com.test，

String  queryString="from com.test.cat";

其中cat为实体类的类名，而不是数据库里面的表名称，大家注意一下，在查询一个类时，hibernate会自动搜索这个类的所有继承类，这就是多态查询。比如上面的cat，如果有继承cat的类，hibernate会把所有实例都查询出来。

2、指定列名

String  queryString="from student s where s.name=?";

或者用as指定，String  queryString="from student as s where s.name=?";

3、投影查询

通常在查询过程中，并非都需要查询一个类的所有属性，有时候只需要查询部分属性，这个时候就需要用select，并且在其后面加上需要查询的属性，代码如下：

String  queryString="select s.age,s.name from student  s";

注意：list里面对应的对象并不是student对象，它返回的是一个数组object\[]，示列如下：

while(i.hasNext)

{

Object \[] o=(Object \[])i.next();

}

在对象数组中，各个属性值是有顺序的。例如o\[0]对应的就是age的值，o\[1]所对应的就是name的值。这种输出方式有时候使用起来不太方便。当然，当只要查询一个元素的时候。比如name，它是String类型的，那么查询出来的返回结果也为String类型，而不是一个数组对象了。例如：

String  queryString="select s.name from student  s";

4、排序

排序的话使用的是关键字order by

例如根据学生编号的降序排序，用学生姓名的升序排序，

String  queryString="from student s order by s.id desc,s.name asc";

5、消除重复记录

使用的关键字为distinct

String  queryString="select distinct s.name form student s";

表示查询不同姓名的学生的姓名

6、调用函数

在查询过程中，有些功能很常用，比如统计符合条件的记录总数，计算平均数据等，对于这些常用的功能，hibernate定义了几个常用的聚集函数

count() 计算符合条件的记录总数

avg()计算符合条件的平均数

sum() 计算符合条件的和

max() 计算符合条件的最大值

min() 计算符合条件的最小值

例如查询数据库中学生的总数，代码如下：

String  queryString="select count(\*) form student ";

执行后，返回值为一个Long型的整数。

7、分组与关键字having

在一个班级中通常有很多学生，且学生分为优、中、良三个等级。如果要统计每个等级中的学生，就需要使用分组，其关键字为group by。代码如下：

String  queryString="select s.level,count(\*) form student  s group by s.level";

该语句用于查询各个等级的学生总数，并且以level分组。若果不想查询所有等级，可以使用having，例如

String  queryString="select s.level,count(\*) form student  s group by s.level having s.level in(1,2)";

表示只查询等级为1和2学生总数。

8、运算符

在hibernate中运算符也经常使用，常用的运算符如下：

(1) 数学运算符：+，-，\*，/

(2 ) 比较运算符：&gt;,&lt;,=,&gt;=,&lt;=,!=,like

(3) 逻辑运算符：and，or，not

（4）其他运算符： in,not in, is null, is not null , is empty, is not empty,between...and...等。

例如用like模糊查询时，有两个可用的通配符：%和\_，%表示长度大于等于0的字符，\_表示长度等于1的字符，例如：查询username中含有a的对象。

String  queryString="from user u where u.username like '%a%'";

查询username中第二个字符为c，且只有三个字符的对象，

String  queryString="from user u where u.username like '\_a\_'";

查询id在1-5之间的实体对象

String  queryString="from user u where u.id between 1 and 5";

大家在设定between...and ...不要把查询范围设置反了，以免发生错误。

其他的运算符用法基本类似，大家可以根据自己需要的选择相应的运算符。