String hql="from Student where sname=:name and sage>:age"; Query query = session.createQuery(hql); query.set 本文主要介绍了Hibernate的几种主要的检索方式:HQL检索方式、QBC检索方式。HQL是Hibernate Query Language的缩写,是官方推荐的查询语言。QBC是Query By Criteria的宿写,是Hibernate提供的一个查询接口。Hibernate是一个轻量级的框架,它允许使用原始SQL语句查询数据库。
一、HQL查询
1:检索类的所有对象
使用HQL语句可以检索出一个类的所有对象,如HQL语句“from Student” 表示检索Student的所有对象。
Query query = session.createQuery("from Student"); List list = query.list(); Iterator it = list.iterator(); while(it.hasNext()){ Student student = (Student)it.next(); System.out.println("id"+student.getId()); System.out.println("name"+student.getName()); } /* for(Iterator it = list.iterator();it.hasNext();){ Student student = (Student)it.next(); System.out.println("id"+student.getId()); System.out.println("name"+student.getName()); } */
2:检索类的某几个属性
Query query = session.createQuery("select Student.name,Student.id from Student"); List list = query.list(); Iterator it = list.iterator(); while(it.hasNext()){ Object[] stu = (Object[])it.next(); System.out.println("name"+stu[0]); System.out.println("id"+stu[1]); }
3:指定别名
要查询时,可能用关键字as指定别名,指定别名可以简化查询,有时必需指定别名才能进行查询。如:
select s.id,s.name from Student as s where s.sno like '%4%';
s就是类Student的别名,注意as可以省略,下面的语句和上面的等效。
select s.id,s.name from Student s where s.sno like %4%;
4:使用where条件子句
在where子句中可以指定查询属性是否为null:is null、not null,其含义分别表示为空和不为空。
from Student s where s.address is null;
5:使用distinct过滤重复值
6:删除对象
7:更新对象值
8:like进行模糊查询
9:order by对结果进行排序
from Student s order by s.age;
from Student s order by s.age,s.no desc;
上面写法为一个升序一个降序。
10:限制每次查询的返回对象数
Query接口提供了两个函数,用于限制每次查询返回的对象数。
11:绑定参数
使用绑定参数可以在程序运行时动态决定一些参数的值。
查询语句中以“ :”开头的变量叫做命名参数,把命名参数和一个具体的值进行绑定的过程叫做绑定参数。