依然接著前面的例子:http://www.bianceng.cn/Programming/Java/201101/23637.htm
示例代碼如下:
1.package com.hb3.pack_01;
2.
3.import java.util.Iterator;
4.import java.util.List;
5. 6.import org.hibernate.Criteria;
7.import org.hibernate.Session;
8.import org.hibernate.SessionFactory;
9.import org.hibernate.cfg.Configuration;
10.import org.hibernate.criterion.DetachedCriteria;
11.import org.hibernate.criterion.Restrictions;
12. 13.import com.hb3.pack_01.model.User;
14. 15.public class BusinessService {
16. 17. public static void main(String[] args) {
18.
19. Configuration config = new Configuration().configure();
20. SessionFactory sessionFactory = config.buildSessionFactory();
21.
22.
23. DetachedCriteria detchedCriteria = DetachedCriteria.forClass(User.class);
24. detchedCriteria.add(Restrictions.ge("age",new Integer(20)));
25.
26. Session session = sessionFactory.openSession();
27. Criteria criteria = detchedCriteria.getExecutableCriteria(session);
28.
29. List<?> users = criteria.list();
30. Iterator<?> iterator = users.iterator();
31. System.out.println("id \t name/age");
32. while(iterator.hasNext()) {
33. User ur = (User) iterator.next();
34. System.out.println(ur.getId() + " \t " + ur.getName() + "/" + ur.getAge());
35. }
36.
37. session.close();
38. sessionFactory.close();
39. }
40.}
Criteria和Session綁定的,但DetachedCriteria則不同。
這是在Hibernate 3中新增的類,目的是為了能夠重復使用Criteria。其使用方法請參看前面對Criteria的介紹:
http://blog.csdn.net/kunshan_shenbin/archive/2008/09/02/2866977.aspx