除了HQL查询外,Hibernate还提供了另外一种,更加贴近面向对象的思想的查询方式。下面来简单的演示一下。
其实使用方法和HQl差不多
package com.bird.hibernate.test; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import com.bird.domain.User; public class CriTest { /** * @param args */ public static void main(String[] args) { cri("bird"); } public static void cri(String name) { Session s = null; try { s = Hibernateutils.getSession(); Criteria c = s.createCriteria(User.class); c.add(Restrictions.eq("name", name));//等于的意思 c.setFirstResult(0); c.setMaxResults(10);//实现分页功能 List<User> list = c.list(); for(User s1 : list){ System.out.println(s1.getId()); } } catch (HibernateException e) { throw e; } finally { if (s != null) s.close(); } } }