一 简介
Hibernate支持三种查询方式:HQL (Hibernate Query Language,Hibernate查询语言)查询、Critcria查询及原生SQL( Native SQL)查询。
HQL是一种面向对象的查询语言,其中没有表和字段的概念,只有类、对象和属性的概念,大家在学习中要注意。
HQL语句功能强大,能满足实际开发中的各种查询要求。HQL查询在形式上和SQL查询相似,但是不要被语法结构上的相似所迷惑,HQL是完全面向对象的,它可以理解继承、多态和关联之类的概念。
二 如何编写HQL语句
HQL语句中除了Java类和属性的名称外,查询语句对大小写不敏感,所以SELect和select是相同的,但是cn.jbit.hibernatdemo.entity.Dept不等价于cn.jbit.hibernatdemo.entity.DEpt。 HQL语句中的关键字建议使用小写字母,如select小写。下面以部门和员工为例,学习常用的HQL语法。
1.from子句
Hibernate中最简单的HQL语句形式如下,以下几条HQL语句都用于查询所有部门。
from cn.jbit.hibernatdemo.entity.Dept
说明:cn.jbit.hibernatdemo.entity.Dept是全限定类名。
from Dept
说明:类名Dept省略了包名。
from Dept as dept
说明:这条HQL语句为持久化类Dept指派了别名dept,可以在HQL语句中使用这个别名。as关键字是可选的。
from Dept dept
2.select子句
select子句用于选取对象和属性。以下几条HQL语句都用来查询所有部门。
select dept from Dept as dept
说明:select后跟的是别名dept。
select dept.deptName from Dept as dept
说明:select子句选取了一个属性deptName,也可以选取多个属性。
3.where子句
where子句用于表达查询的限制条件。
from Dept where deptName ='SALES’
说明:这条HQL语句用于查询名称是SALES的部门。在where子句中直接使用属性名deptNarne。
from Dept as dept where dept.deptName=‘SALES’
说明:这条HQL语句用于查询名称是SALES的部门。这条HQL语句指派了别名,在where
子句中使用了完整的属性名dep t.deptName。
from Dept dept where dept.location is not null
说明:这条HQL语句用于查询地址不为空的部门。
4.使用表达式
表达式一般用在where子句中。以下两个HQL查询语句在where子句中分别使用了lower()函数和year()函数。
from Dely dept where lower(dept.deptName)=‘sales’
说明:这条HQL语句用于查询名称是sales的部门,不区分大小写。lower()函数用于把字符串
中的每个字母改为小写。
说明:这条HQL语句用于查询1980年入职的员工。year()函数用于获取日期字段的年份。
5. order by子句
order by子句用于按指定属性排序。
from Emp order by hireDate asc
说明:这条HQL语句用于查询所有员工,并按员工人职时间升序排序。关键字asc或desc是可选的,用于指明按照升序或者降序进行排序,默认按升序排列。
from Emp order by hireDate, salary desc
说明:这条HQL语句用于查询所有员工,先按员工人职时间升序,然后时间相同的再按员工工资降序排序。
三 案例
===================sql 脚本========================
CREATE TABLE department
(
deptId SMALLINT PRIMARY KEY,
departName VARCHAR(20) NOT NULL,
address VARCHAR(20)
)
;
CREATE TABLE student
(
stuId INT PRIMARY KEY AUTO_INCREMENT,
stuName VARCHAR(20) NOT NULL,
gender VARCHAR(2),
age SMALLINT,
address VARCHAR(200) DEFAULT '学生宿舍',
deptIdd SMALLINT,
FOREIGN KEY(deptIdd) REFERENCES department(deptId)
)AUTO_INCREMENT=100
;
INSERT INTO department VALUES (10,'计算机系','计算机楼302');
INSERT INTO department VALUES (11,'艺术系','艺术楼211');
INSERT INTO department VALUES (12,'经管系','商学院911');
INSERT INTO department VALUES (13,'工程系','工程楼301');
INSERT INTO department VALUES (14,'土木系','建筑楼355');
--
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('王燕','女',18,DEFAULT,10);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('张栋','男',21,DEFAULT,10);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('李波','男',21,DEFAULT,11);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('陈建','男',19,DEFAULT,11);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('王江洪','男',25,DEFAULT,12);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('潘将','男',24,DEFAULT,13);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('张斌','男',22,DEFAULT,14);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('张斌','女',20,DEFAULT,10);
--
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('刘大海','男',28,DEFAULT,10);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('刘德华','男',31,DEFAULT,10);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('周润发','男',41,DEFAULT,11);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('张学友','男',37,DEFAULT,11);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('周星驰','男',42,DEFAULT,12);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('刘亦菲','女',24,DEFAULT,13);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('胡歌','男',32,DEFAULT,14);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('范冰冰','女',20,DEFAULT,10);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('杨幂','女',26,DEFAULT,14);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('刘涛','女',27,DEFAULT,13);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('周迅','女',21,DEFAULT,13);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('古力娜扎','女',19,DEFAULT,10);
INSERT INTO Student(stuName,gender,age,address,deptIdd) VALUES ('黑山老妖','妖',99,DEFAULT,12);
---------------------------------mapper映射文件--------------------------------
<hibernate-mapping package="com.obtk.entitys">
<class name="StudentEntity" table="student">
<id name="stuId" type="java.lang.Integer">
<column name="stuId" />
<generator class="native"></generator>
</id>
<property name="stuName" type="java.lang.String">
<column name="stuName" length="20" />
</property>
<property name="gender" type="java.lang.String">
<column name="gender" length="2" />
</property>
<property name="age" type="integer">
<column name="age" />
</property>
<property name="address" type="java.lang.String">
<column name="address" length="200" />
</property>
<property name="deptIdd" type="integer">
<column name="deptIdd" />
</property>
</class>
</hibernate-mapping>
3.1 案例1===》最简单的hql查询
package com.obtk.test;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.obtk.entitys.UserEntity;
import com.obtk.utils.HiberUtil;
public class QueryTest1 {
public static void main(String[] args) {
Session session=null;
String hqlSql="from UserEntity";
try {
session=HiberUtil.getSession();
Query qy=session.createQuery(hqlSql);
List<UserEntity> userList=qy.list();
for(UserEntity user : userList){
System.out.println(user.getUserId()+"\t"+user.getUserName()
+"\t"+user.getEmail());
}
} catch (HibernateException e) {
e.printStackTrace();
}finally{
HiberUtil.closeSession();
}
}
}
3.2 案例2==》参数设置及模糊查询
package com.obtk.test;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.obtk.entitys.StudentEntity;
import com.obtk.entitys.UserEntity;
import com.obtk.utils.HiberUtil;
public class QueryTest2 {
public static void main(String[] args) {
Session session=null;
String hqlSql="from StudentEntity where stuName like ?";
try {
session=HiberUtil.getSession();
Query qy=session.createQuery(hqlSql);
qy.setString(0, "%张%");
List<StudentEntity> stuList=qy.list();
for(StudentEntity stu : stuList){
System.out.println(stu.getStuId()+"\t"+stu.getStuName()+"\t"
+stu.getGender());
}
} catch (HibernateException e) {
e.printStackTrace();
}finally{
HiberUtil.closeSession();
}
}
}
3.3 案例3==》setParameter的用法
package com.obtk.test;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.obtk.entitys.StudentEntity;
import com.obtk.entitys.UserEntity;
import com.obtk.utils.HiberUtil;
public class QueryTest4 {
public static void main(String[] args) {
Session session=null;
String hqlSql="from StudentEntity where stuName like ? and age>?";
try {
session=HiberUtil.getSession();
Query qy=session.createQuery(hqlSql);
//如果不知道参数是说明类型,就用qy.setParameter
qy.setParameter(0, "%张%");
qy.setParameter(1, 20);
List<StudentEntity> stuList=qy.list();
for(StudentEntity stu : stuList){
System.out.println(stu.getStuId()+"\t"+stu.getStuName()+"\t"
+stu.getGender()+"\t"+stu.getAge());
}
} catch (HibernateException e) {
e.printStackTrace();
}finally{
HiberUtil.closeSession();
}
}
}
3.4 案例4==》参数绑定及setProperties的用法
package com.obtk.test;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.obtk.entitys.ConditionEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.entitys.UserEntity;
import com.obtk.utils.HiberUtil;
public class QueryTest6 {
public static void main(String[] args) {
Session session=null;
//用properties来解决过多的问题
String hqlSql="from StudentEntity where stuName like :theName and age>:theAge" +
" and gender=:theGender";
try {
session=HiberUtil.getSession();
Query qy=session.createQuery(hqlSql);
//用properties来解决过多的问题
ConditionEntity theCondition=new ConditionEntity("%张%", 20, "男");
qy.setProperties(theCondition);
List<StudentEntity> stuList=qy.list();
for(StudentEntity stu : stuList){
System.out.println(stu.getStuId()+"\t"+stu.getStuName()+"\t"
+stu.getGender()+"\t"+stu.getAge());
}
} catch (HibernateException e) {
e.printStackTrace();
}finally{
HiberUtil.closeSession();
}
}
}