您的位置:首页 > 其它

[置顶] 【SSH】使用HQL查询数据

2016-11-28 20:29 204 查看

一、前言

小编先前使用过SQL,基本语法自己也会使用。后来在项目中遇到了HQL,稍微有点不同,他到底是什么呢?

二、什么是HQL?

HQL(Hibernate Query Language)是Hibernate提供的一种面向对象的查询语言,HQL提供了更加丰富灵活的特性、强大的查询能力,HQL提供了更接近传统的SQL语句的查询语法。

三、HQL语法分析

3.1 完整的HQL语句结构:

[select [distinct] field_ list|update |delete ]  from EntityName
[where where_ condition]
[group  by group_by_expression ]
[having where where_condition]
[order by order_by_expression [ASC | DESC]]


使用HQL需要以下四步:

(1)得到Session对象

(2)编写HQL语句

(3)创建Query对象

(4)执行查询,得到结果。


3.2 查询

select子句语法:

select [distinct] field_list from EntityName;


语法中:

distinct可以去除结果中重复的数据。

EntityName是持久化类名,也就是实体名。

field_list是持久化类字段列表,也就是实体的属性。


动态构造对象

可以利用HQL提供的动态构造实例的功能对这些数据进行封装。

动态构造对象语法:

//通式
select new EntityName(alias.field[,....]) from Entity as alias;

//具体例子
select new User(user.name,user.age) from Useras user;


在语法中:

EntityName是持久化类名;

alias为持久化类别名;

field是持久化类中的字段;


3.3 更新update子句

update [from] EntityName as alias set alias.field = value[,...] where where_condition


在语法中:

EntityName 是持久化类名;

field 是持久化类中的字段;


3.4 删除delete子句

delete [from] EntityName as alias where where_condition


在语法中,EntityName是持久化类名;

3.5 参数绑定

按名称绑定

在HQL中定义命名参数要用“:”开头,用Query接口的query.setParameter(fieldname.value)方法设定数值。

示例:

Query query = session.creteQuery(
"form User user where user.name=:name and user.age=:age");

query.setString("name",name);
query.setString("age",age);


按位置绑定

在HQL查询语句中中“?”来定义参数的位置,用Query接口的query.setParameter(index,value)方法设定参数值。

示例:

Query query = session.creteQuery(
"form User user where user.name=? and user.age=?");

query.setString(0,name);
query.setString(1,age);


温馨提示:

在实际开发中,提倡使用按名称绑定参数,因为这不但可以提供非常好的程序可读性,而且还能提高程序的易维护性,因为当查询参数的位置发生变化时,按名称绑定不需要调整程序的代码。

3.6 order by排序

order by 子句的语法:

[select [distinct] field_ list|update |delete ]  from
EntityName [where where_ condition] [order by order_by_expression [ASC | DESC]]


在语法中:

EntityName 是持久化类名;

order_by_expression 是指定要排序字段或表达式;


3.7 分组

group by 子句

group by 子句语法:

[select [distinct] field_ list|update |delete ]  from
EntityName [where where_ condition] [group  by group_by_expression ]


having 子句

having 子句的语法:

[select [distinct] field_ list|update |delete ]  from
EntityName [where where_ condition] [group  by group_by_expression ] [having where where_condition] 


在语法中,having关键字一定要和group by 搭配使用。

小结

对比学习,在以后的使用过程中,我们会越来越强, 加油!everybody can do it!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: