示例代码如下:
- package com.hb3.pack_01;
- import java.util.Iterator;
- import java.util.List;
- import org.hibernate.Criteria;
- import org.hibernate.Hibernate;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.criterion.Example;
- import org.hibernate.criterion.Order;
- import org.hibernate.criterion.ProjectionList;
- import org.hibernate.criterion.Projections;
- import org.hibernate.criterion.Property;
- import org.hibernate.criterion.Restrictions;
- import org.hibernate.type.Type;
- import com.hb3.pack_01.model.User;
- public class BusinessService {
- public static void main(String[] args) {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- Criteria criteria = session.createCriteria(User.class);
- criteria.addOrder(Order.asc("age"));
- List<?> users = criteria.list();
- printUserInfo(users);
-
- criteria = session.createCriteria(User.class);
- criteria.add(Restrictions.gt("age", new Integer(22)));
- criteria.add(Restrictions.lt("age", new Integer(27)));
- users = criteria.list();
- printUserInfo(users);
-
- criteria = session.createCriteria(User.class);
- criteria.add(Restrictions.or(
- Restrictions.eq("age", new Integer(23)),
- Restrictions.isNull("age")
- ));
- users = criteria.list();
- printUserInfo(users);
-
- criteria = session.createCriteria(User.class);
- criteria.add(Restrictions.sqlRestriction("{alias}.name LIKE (?)", "%ya%", Hibernate.STRING));
- users = criteria.list();
- printUserInfo(users);
-
- criteria = session.createCriteria(User.class);
- Integer[] ages = {new Integer(26), new Integer(28)};
- Type[] types = {Hibernate.INTEGER, Hibernate.INTEGER};
- criteria.add(Restrictions.sqlRestriction("{alias}.age BETWEEN (?) AND (?)", ages, types));
- users = criteria.list();
- printUserInfo(users);
-
- criteria = session.createCriteria(User.class);
- criteria.setFirstResult(3);
- criteria.setMaxResults(2);
- users = criteria.list();
- printUserInfo(users);
-
- criteria = session.createCriteria(User.class);
- criteria.setProjection(Projections.rowCount());
- users = criteria.list();
- Iterator<?> iterator = users.iterator();
- while (iterator.hasNext()) {
- System.out.println(iterator.next());
- }
-
- criteria = session.createCriteria(User.class);
- criteria.setProjection(Projections.avg("age"));
- users = criteria.list();
- iterator = users.iterator();
- while (iterator.hasNext()) {
- System.out.println(iterator.next());
- }
-
- criteria = session.createCriteria(User.class);
- criteria.setProjection(Projections.groupProperty("age"));
- users = criteria.list();
- iterator = users.iterator();
- while (iterator.hasNext()) {
- System.out.println(iterator.next());
- }
-
- ProjectionList projectionList = Projections.projectionList();
- projectionList.add(Projections.groupProperty("age"));
- projectionList.add(Projections.groupProperty("name"));
- projectionList.add(Projections.rowCount());
- criteria = session.createCriteria(User.class);
- criteria.setProjection(projectionList);
- users = criteria.list();
- iterator = users.iterator();
- while(iterator.hasNext()) {
- Object[] o = (Object[]) iterator.next();
- System.out.println(o[0] + ""t" + o[1] + ""t" + o[2]);
- }
-
- criteria = session.createCriteria(User.class);
- criteria.add(Property.forName("name").like("%ya%"));
- criteria.addOrder(Property.forName("age").desc());
- users = criteria.list();
- printUserInfo(users);
-
- User user = new User();
- user.setAge(new Integer(26));
- criteria = session.createCriteria(User.class);
- criteria.add(Example.create(user));
- users = criteria.list();
- printUserInfo(users);
-
- session.close();
- sessionFactory.close();
- }
-
- public static void printUserInfo(List<?> users){
-
- Iterator<?> iterator = users.iterator();
- System.out.println("id "t name/age");
- while (iterator.hasNext()) {
- User user = (User) iterator.next();
- System.out.println(user.getId() + " "t " + user.getName() + "/" + user.getAge());
- }
- }
- }
运行结果如下:
15:41:36,312 WARN ConfigurationFactory:127 - No configuration
found. Configuring ehcache from ehcache-failsafe.xml found in the
classpath:
jar:file:/D:/Java/MyEclipse%206.0/workspace/hb3demo/ehcache-1.2.3.jar!/ehcache-failsafe.xml
15:41:36,750
WARN EhCacheProvider:93 - Could not find configuration
[org.hibernate.cache.UpdateTimestampsCache]; using defaults.
15:41:36,781 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from user this_ order by this_.age asc
id name/age
11 yangye/null
12 yangye/null
9 yangye/23
10 yangye/23
2 chenyan/26
1 shenbin/28
Hibernate:
select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_
from user this_ where this_.age>? and this_.age<?
id name/age
2 chenyan/26
9 yangye/23
10 yangye/23
Hibernate:
select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_
from user this_ where (this_.age=? or this_.age is null)
id name/age
9 yangye/23
10 yangye/23
11 yangye/null
12 yangye/null
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from user this_ where this_.name LIKE (?)
id name/age
2 chenyan/26
9 yangye/23
10 yangye/23
11 yangye/null
12 yangye/null
Hibernate:
select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_
from user this_ where this_.age BETWEEN (?) AND (?)
id name/age
1 shenbin/28
2 chenyan/26
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from user this_ limit ?, ?
id name/age
10 yangye/23
11 yangye/null
Hibernate: select count(*) as y0_ from user this_
6
Hibernate: select avg(this_.age) as y0_ from user this_
25.0
Hibernate: select this_.age as y0_ from user this_ group by this_.age
null
23
26
28
Hibernate: select this_.age as y0_, this_.name as y1_, count(*) as y2_ from user this_ group by this_.age, this_.name
null yangye 2
23 yangye 2
26 chenyan 1
28 shenbin 1
Hibernate:
select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_
from user this_ where this_.name like ? order by this_.age desc
id name/age
2 chenyan/26
9 yangye/23
10 yangye/23
11 yangye/null
12 yangye/null
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from user this_ where (this_.age=?)
id name/age
2 chenyan/26
注意:
Restrictions的几个常用限定查询方法如下表所示:
方法 |
说明 |
Restrictions.eq |
等于 |
Restrictions.allEq |
使用Map,使用key/value进行多个等于的比对 |
Restrictions.gt |
大于 > |
Restrictions.ge |
大于等于 >= |
Restrictions.lt |
小于 < |
Restrictions.le |
小于等于 <= |
Restrictions.between |
对应SQL的BETWEEN子句 |
Restrictions.like |
对应SQL的LIKE子句 |
Restrictions.in |
对应SQL的in子句 |
Restrictions.and |
and关系 |
Restrictions.or |
or关系 |
Restrictions.sqlRestriction |
SQL限定查询 |
此外,Criteria还可以进行复合查询。即在原有的查询基础上再进行查询,例如在Room对User的一对多关系中,在查询出所有的Room資料之后,希望再查询users中"age"为30的user資料:
- Criteria roomCriteria = session.createCriteria(Room.class);
- Criteria userCriteria = roomCriteria.createCriteria("users");
- userCriteria.add(Restrictions.eq("age", new Integer(30)));
- List rooms = roomCriteria.list(); // 只列出users属性中有user之"age"为30的Room
- Iterator iterator = rooms.iterator();
这个涉及到对象的关联映射,在后续章节中还会着重讲述。
ExtJS教程-
Hibernate教程-
Struts2 教程-
Lucene教程