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 ...
随机推荐
- Time Out 访问数据库超时处理 .NET
using System.Reflection; using System.Data.SqlClient; TransactionSelectTableAdapter adapter = new Tr ...
- android通讯录导航栏源码(一)
通讯录导航栏源码: 1.activity package com.anna.contact.activity; import java.util.ArrayList; import java.util ...
- SQL Server 已提交读快照 测试
1. 打开数据库 已提交读快照 选项 2. 数据库 已提交读快照 模式下的测试 a) 测试表 Test b) 开启事务1,更新数据C2 = '200'(未提交) BEGIN TRAN ' WHERE ...
- git 删除本地分支和远程分支、本地代码回滚和远程代码库回滚
[git 删除本地分支] git branch -D br [git 删除远程分支] git push origin :br (origin 后面有空格) git代码库回滚: 指的是将代码库某分支退 ...
- Three.js学习笔记 – “我和小伙伴都惊呆了”的特效和Three.js初探
什么是Three.js three.js是JavaScript编写的WebGL第三方库.提供了非常多的3D显示功能.Three.js 是一款运行在浏览器中的 3D 引擎,你可以用它创建各种三维场景,包 ...
- 点击上下页,实现图片滚动的jquery代码
<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content=&q ...
- jQuery 随滚动条滚动效果 (适用于内容页长文章)
直接入题! 当内容页比较长的时候,网站右侧一直是空白,不如放点有用的东西给用户看,最好不要放广告,因为那样很邪恶,你懂的. 好吧,昨天写了这个东西,jQuery滚动随动区块,代码如下: //侧栏随动 ...
- django随笔说明
最近学习了vamei的快速Python教程,想着语法学了不用就要忘记,总要拿点东西来练练手,然后又开始学习Django,也算是顺势而为吧. 现在学Django,是跟着教程djangobook学的,内容 ...
- PHP中简单的图形处理
PHP中简单的图形处理 计应134凌豪 1.加载GD库 GD库是一个开放的动态创建图像.源代码公开的函数库,可以从官方网站http://www.boutell.com/gd处下载.目前,GD库支持GI ...
- sqlmap的详细使用
各项参数讲的太仔细了,对于只会几个参数的我来说,太受用了. 先mark下 http://drops.wooyun.org/tips/143 http://drops.wooyun.org/tips/4 ...