示例代码如下:
- package com.hb3.pack_01;
- import java.util.Iterator;
- import java.util.List;
- import org.hibernate.Criteria;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.criterion.DetachedCriteria;
- import org.hibernate.criterion.Restrictions;
- 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();
-
-
- DetachedCriteria detchedCriteria = DetachedCriteria.forClass(User.class);
- detchedCriteria.add(Restrictions.ge("age",new Integer(20)));
-
- Session session = sessionFactory.openSession();
- Criteria criteria = detchedCriteria.getExecutableCriteria(session);
-
- List<?> users = criteria.list();
- Iterator<?> iterator = users.iterator();
- System.out.println("id \t name/age");
- while(iterator.hasNext()) {
- User ur = (User) iterator.next();
- System.out.println(ur.getId() + " \t " + ur.getName() + "/" + ur.getAge());
- }
-
- session.close();
- sessionFactory.close();
- }
- }
Criteria和Session绑定的,但DetachedCriteria则不同。
这是在Hibernate 3中新增的类,目的是为了能够重复使用Criteria。其使用方法请参看前面对Criteria的介绍:
ExtJS教程-
Hibernate教程-
Struts2 教程-
Lucene教程