HIbernate-查询语句

Hibernate Query Language (HQL) 是一个面向对象的查询语言,与Sql相似, 相对于sql对表和列的操作, HQL是对持久对象和他们的属性进行操作.

HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.

Although you can use SQL statements directly with Hibernate using Native SQL but I would recommend to use HQL whenever possible to avoid database portability hassles, and to take advantage of Hibernate's SQL generation and caching strategies.

虽然您可以使用SQL语句直接与Hibernate使用本机SQL但我建议使用HQL尽可能避免数据库的可移植性的麻烦,并利用Hibernate的SQL生成和缓存策略。

Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive(灵敏的) in HQL.

FROM Clause(条约)

You will use FROM clause if you want to load a complete persistent objects into memory. Following is the simple syntax of using FROM clause:

String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();

If you need to fully qualify a class name in HQL, just specify the package and class name as follows:

String hql = "FROM com.hibernatebook.criteria.Employee";
Query query = session.createQuery(hql);
List results = query.list();

AS Clause

The AS clause can be used to assign aliases to the classes in your HQL queries, specially when you have long queries. For instance, our previous simple example would be the following:

String hql = "FROM Employee AS E";
Query query = session.createQuery(hql);
List results = query.list();

The AS keyword is optional and you can also specify the alias directly after the class name, as follows:

String hql = "FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

SELECT Clause

The SELECT clause provides more control over the result set than the from clause. If you want to obtain few properties of objects instead of the complete object, use the SELECT clause. Following is the simple syntax of using SELECT clause to get just first_name field of the Employee object:

String hql = "SELECT E.firstName FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

It is notable here that Employee.firstName is a property of Employee object rather than a field of the EMPLOYEE table.

WHERE Clause

If you want to narrow the specific objects that are returned from storage, you use the WHERE clause. Following is the simple syntax of using WHERE clause:

String hql = "FROM Employee E WHERE E.id = 10";
Query query = session.createQuery(hql);
List results = query.list();

ORDER BY Clause

To sort your HQL query's results, you will need to use the ORDER BY clause. You can order the results by any property on the objects in the result set either ascending (ASC) or descending (DESC). Following is the simple syntax of using ORDER BY clause:

String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();

If you wanted to sort by more than one property, you would just add the additional properties to the end of the order by clause, separated by commas as follows:

String hql = "FROM Employee E WHERE E.id > 10 " +
"ORDER BY E.firstName DESC, E.salary DESC ";
Query query = session.createQuery(hql);
List results = query.list();

GROUP BY Clause

This clause lets Hibernate pull information from the database and group it based on a value of an attribute and, typically, use the result to include an aggregate value. Following is the simple syntax of using GROUP BY clause:

String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " +
"GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();

Using Named Paramters

Hibernate supports named parameters in its HQL queries. This makes writing HQL queries that accept input from the user easy and you do not have to defend against SQL injection attacks. Following is the simple syntax of using named parameters:

String hql = "FROM Employee E WHERE E.id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();

UPDATE Clause

Bulk updates are new to HQL with Hibernate 3, and deletes work differently in Hibernate 3 than they did in Hibernate 2. The Query interface now contains a method called executeUpdate() for executing HQL UPDATE or DELETE statements.

The UPDATE clause can be used to update one or more properties of an one or more objects. Following is the simple syntax of using UPDATE clause:

String hql = "UPDATE Employee set salary = :salary "  +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

DELETE Clause

The DELETE clause can be used to delete one or more objects. Following is the simple syntax of using DELETE clause:

String hql = "DELETE FROM Employee "  +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

INSERT Clause

HQL supports INSERT INTO clause only where records can be inserted from one object to another object. Following is the simple syntax of using INSERT INTO clause:

String hql = "INSERT INTO Employee(firstName, lastName, salary)"  +
"SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Aggregate Methods

HQL supports a range of aggregate methods, similar to SQL. They work the same way in HQL as in SQL and following is the list of the available functions:

S.N. Functions Description
1 avg(property name) The average of a property's value
2 count(property name or *) The number of times a property occurs in the results
3 max(property name) The maximum value of the property values
4 min(property name) The minimum value of the property values
5 sum(property name) The sum total of the property values

The distinct keyword only counts the unique values in the row set. The following query will return only unique count:

String hql = "SELECT count(distinct E.firstName) FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

Pagination using Query

There are two methods of the Query interface for pagination.

S.N. Method & Description
1 Query setFirstResult(int startPosition)

This method takes an integer that represents the first row in your result set, starting with row 0.

2 Query setMaxResults(int maxResult)

This method tells Hibernate to retrieve a fixed number maxResults of objects.

Using above two methods together, we can construct a paging component in our web or Swing application. Following is the example which you can extend to fetch 10 rows at a time:

String hql = "FROM Employee";
Query query = session.createQuery(hql);
query.setFirstResult(1);
query.setMaxResults(10);
List results = query.list(); resource:http://www.tutorialspoint.com/hibernate/hibernate_query_language.htm

hibernate总结四的更多相关文章

  1. >hibernate的四种状态

    hibernate的四种状态 1.临时状态 与数据库中没有相对应的数据,也不在session的管理之中,一般是新new出来的对象 2.持久化状态 对象在session的管理中,最后会在事务提交后,在数 ...

  2. SSH框架之hibernate《四》

    hibernate第四天     一.JPA相关概念         1.1JPA概述             全称是:Java Persistence API.是sun公司推出的一套基于ORM的规范 ...

  3. hibernate学习四(关系映射一对一与组件映射)

    一.关系映射简介 在数据库中,表与表的关系,仅有外键.但使用hibernate后,为面向对象的编程,对象与对象的关系多样化:如 一对一,一对多,多对多,并具有单向和双向之分. 开始练习前,复制上一次项 ...

  4. hibernate(四)ID生成策略

    一.ID生成策略配置 1.ID生成方式在xml中配置方式: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping P ...

  5. 攻城狮在路上(壹) Hibernate(四)--- 对象标识符(OID)生成机制

    Hibernate使用对象标识符(OID)来建立内存中对象和数据库表中记录的对应关系,对象的OID和数据库的主键对应.为了保证OID的唯一性和不可变性,应该让Hibernate来为OID赋值.Hibe ...

  6. hibernate篇章四-- Hibernate配置文件中hiberante.hbm2ddl.auto四个参数的配置

    我们在搭建环境的时候,在配置文件中有一个属性标签为: <property name="hibernate.hbm2ddl.auto">     </propert ...

  7. Java框架之Hibernate(四)

    本文主要介绍: 1 悲观锁和乐观锁 2 使用版本号控制并发访问 3 flush方法和批量更新的问题 4 DetachedCriteria 5 N + 1 次查询 6 使用sql进行查询 7 注解方式 ...

  8. Hibernate的四种查询方式(主键查询,HQL查询,Criteria查询,本地sql查询)和修改和添加

    Hibernate的添加,修改,查询(三种查询方式)的方法: 案例演示: 1:第一步,导包,老生常谈了都是,省略: 2:第二步,创建数据库和数据表,表结构如下所示: 3:第三步创建实体类User.ja ...

  9. Hibernate第四天——查询方式

    Hibernate入门最后一天第四天,我们进行查询方式的更进一步的细化: 先看一下大致的Hibernate的提供的查询的方式: 1.对象导航查询 2.OID查询 3.HQL查询 4.QBC查询 5.本 ...

  10. Hibernate(十四)缓存

    一.什么是缓存 缓存是介于应用程序和永久必数据存储源之间,目的是为了降低应用程序直接读写永久必数据存储源的频率,从而提高运行性能 缓存通常是在内存中的如: Office中的Word.excel Hib ...

随机推荐

  1. C#—Dev XtraTabControl动态增加Tab和关闭选项卡方法

    C#—Dev XtraTabControl动态增加Tab和关闭选项卡方法,有需要的朋友可以参考下. 记录一下以免以后忘了 添加using DevExpress.XtraTab; 双击listview增 ...

  2. sql server中将一个表中的部分数据插入到另一个表中

    可以通过存储过程完成,也可以通过在库名上右击“新建查询”执行.语句其实基本相同. 1. 存储过程: CREATE PROCEDURE pro1 as insert into tableB (field ...

  3. 【深搜加剪枝】【HDU1455】【Sticks】

    题目大意:有一堆木棍 由几个相同长的木棍截出来的,求那几个相同长的木棍最短能有多短? 深搜+剪枝 具体看代码 #include <cstdio> #include <cstdlib& ...

  4. js 去重 字符串 [123123,123123,345435,33467,45645,343467,879,45645]

    function unique(dislodgeArr) { var ret = [] var hash = {} var datasource = new Array(); var array= d ...

  5. DSOframer 无法正常加载的解决方案

    不了解 DSOframer 的朋友,可以先参考文章 DSOframer 的简单介绍和资源整理. 在使用 DSOframer 时,经常会碰到各种奇奇怪怪的问题,最常见的就是控件不能正常加载.大家可以按下 ...

  6. Android 打开系统最近任务及最近应用方法

    Class serviceManagerClass; try { serviceManagerClass = Class.forName("android.os.ServiceManager ...

  7. 【IOS学习基础】NSObject.h学习

    一.<NSObject>协议和代理模式 1.在NSObject.h头文件中,我们可以看到 // NSObject类是默认遵守<NSObject>协议的 @interface N ...

  8. C语言strcmp()函数:比较字符串(区分大小写)

    头文件:#include <string.h> strcmp() 用来比较字符串(区分大小写),其原型为: int strcmp(const char *s1, const char *s ...

  9. js的两种数据类型

    js中的数据类型总体来说分为两种,他们分别是: 1 值类型(基本类型):数值型(Number),字符类型(String),布尔值型(Boolean),null 和 underfined 2 引用类型( ...

  10. [Linked List]Sort List

    otal Accepted: 59473 Total Submissions: 253637 Difficulty: Medium Sort a linked list in O(n log n) t ...