hibernate总结四
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总结四的更多相关文章
- >hibernate的四种状态
hibernate的四种状态 1.临时状态 与数据库中没有相对应的数据,也不在session的管理之中,一般是新new出来的对象 2.持久化状态 对象在session的管理中,最后会在事务提交后,在数 ...
- SSH框架之hibernate《四》
hibernate第四天 一.JPA相关概念 1.1JPA概述 全称是:Java Persistence API.是sun公司推出的一套基于ORM的规范 ...
- hibernate学习四(关系映射一对一与组件映射)
一.关系映射简介 在数据库中,表与表的关系,仅有外键.但使用hibernate后,为面向对象的编程,对象与对象的关系多样化:如 一对一,一对多,多对多,并具有单向和双向之分. 开始练习前,复制上一次项 ...
- hibernate(四)ID生成策略
一.ID生成策略配置 1.ID生成方式在xml中配置方式: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping P ...
- 攻城狮在路上(壹) Hibernate(四)--- 对象标识符(OID)生成机制
Hibernate使用对象标识符(OID)来建立内存中对象和数据库表中记录的对应关系,对象的OID和数据库的主键对应.为了保证OID的唯一性和不可变性,应该让Hibernate来为OID赋值.Hibe ...
- hibernate篇章四-- Hibernate配置文件中hiberante.hbm2ddl.auto四个参数的配置
我们在搭建环境的时候,在配置文件中有一个属性标签为: <property name="hibernate.hbm2ddl.auto"> </propert ...
- Java框架之Hibernate(四)
本文主要介绍: 1 悲观锁和乐观锁 2 使用版本号控制并发访问 3 flush方法和批量更新的问题 4 DetachedCriteria 5 N + 1 次查询 6 使用sql进行查询 7 注解方式 ...
- Hibernate的四种查询方式(主键查询,HQL查询,Criteria查询,本地sql查询)和修改和添加
Hibernate的添加,修改,查询(三种查询方式)的方法: 案例演示: 1:第一步,导包,老生常谈了都是,省略: 2:第二步,创建数据库和数据表,表结构如下所示: 3:第三步创建实体类User.ja ...
- Hibernate第四天——查询方式
Hibernate入门最后一天第四天,我们进行查询方式的更进一步的细化: 先看一下大致的Hibernate的提供的查询的方式: 1.对象导航查询 2.OID查询 3.HQL查询 4.QBC查询 5.本 ...
- Hibernate(十四)缓存
一.什么是缓存 缓存是介于应用程序和永久必数据存储源之间,目的是为了降低应用程序直接读写永久必数据存储源的频率,从而提高运行性能 缓存通常是在内存中的如: Office中的Word.excel Hib ...
随机推荐
- JAVA Socket无参构造方法的使用
1.Socket类的构造方法很多,只有无参构造方法不会尝试建立连接,其他构造方法,都会尝试建立连接的,如果建立连接失败,将会抛出异常.如果想为Socket设定连接超时时间,此时就需要使用无参构造方法, ...
- C#获取URL参数值(NameValueCollection)
在写程序的时候,我们经常需要对页面进行传参数,比如page?id=1234,那么在page这个页面中就直接可以使用string id = Request.QueryString["id&qu ...
- HTML注释简介
HTML注释简介 在编写HTML代码时,我们经常要在一些关键代码旁做一下注释,这样做的好处很多,比如:方便理解.方便查找或方便项目组里的其它程序员了解你的代码,而且可以方便以后你对自己代码进行修改 ...
- Home键屏蔽
公司要开发一款智能终端,设备中预装了本公司开发的软件,但是为了避免用户进入Android系统的界面,这个时候我们就需要对其中的按键加以屏蔽,尤其是Home键,在普通的情况下,当我们点击Home按键的时 ...
- Hibernate工作原理及为什么要用?(转http://www.cnblogs.com/javaNewegg/archive/2011/08/28/2156521.html)
原理:1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件2.由hibernate.cfg.xml中的<mapping resou ...
- jquery.session.js使用
// jquery.session.js 简单使用方法 添加数据 $.session.set('key', 'value') 删除数据 $.session.remove('key'); 获 ...
- 一次非典型的SQL报错
昨天调试一个表值函数,结果出现了这个错误. mplicit conversion of varchar value to varchar cannot be performed because the ...
- js查找元素
1.className <!DOCTYPE html> <html> <head lang="en"> <meta charset=&qu ...
- IIS7.0 部署wcf 404或者配置MIME(转)
WCF部署在IIS下,报错如下: 应用程序“DEFAULT WEB SITE/IMF”中的服务器错误 Internet 信息服务 7.0 错误摘要 HTTP 错误 404.3 - Not Found由 ...
- PHP中的数组方法及访问方法总结
一.数组操作的基本函数 数组的键名和值 array_values($arr);获得数组的值 array_keys($arr);获得数组的键名 array_flip($arr);数组中的值与键名互换(如 ...