Hibernate的Criteria查询接口

下面的测试在 hibernate-core-5.0.7.Final.jar 下可以正常使用



public class TestQBC {
	
	/**
	 * 不带条件的查询
	 */
	@Test
	public void test01() {
		//创建Criteria对象
		Session session = HibernateUtils.getCurrentSession() ;
		Transaction tr = session.beginTransaction() ;
		Criteria c = session.createCriteria(User.class) ;

		printUsers(c.list());
		
	}
	
	
	/**
	 * 模糊查询
	 */
	@Test
	public void test02() {
		Session session = HibernateUtils.getCurrentSession() ;
		Transaction tr = session.beginTransaction() ;
		Criteria c = session.createCriteria(User.class) ;
		//设置条件
		c.add(Restrictions.like("name", "%路人%")) ;

		printUsers(c.list());
		
	}

	
	/**
	 * and的多条件查询
	 */
	@Test
	public void test03() {
		Session session = HibernateUtils.getCurrentSession() ;
		Transaction tr = session.beginTransaction() ;
		Criteria c = session.createCriteria(User.class) ;
		//设置条件
		c.add(Restrictions.like("name", "%路人%")) ;
		c.add(Restrictions.gt("age", 10)) ;

		printUsers(c.list());
		
	}
	
	
	/**
	 * or的多条件查询
	 */
	@Test
	public void test04() {
		Session session = HibernateUtils.getCurrentSession() ;
		Transaction tr = session.beginTransaction() ;
		Criteria c = session.createCriteria(User.class) ;
		//设置条件
		//名字带路人的或者年龄大于10岁的
		c.add(Restrictions.or(Restrictions.like("name", "%路人%"), 
								Restrictions.gt("age", 10))) ;

		printUsers(c.list());
		
	}
	
	
	/**
	 * between and条件查询
	 */
	@Test
	public void test05() {
		Session session = HibernateUtils.getCurrentSession() ;
		Transaction tr = session.beginTransaction() ;
		Criteria c = session.createCriteria(User.class) ;
		//设置条件
		//名字带路人的或者年龄10-30之间
		c.add(Restrictions.between("age" , 10 , 30)) ;

		printUsers(c.list());
		
	}
	
	/**
	 * 分页
	 */
	@Test
	public void test06() {
		Session session = HibernateUtils.getCurrentSession() ;
		Transaction tr = session.beginTransaction() ;
		Criteria c = session.createCriteria(User.class) ;
		
		//第几条数据,索引从0开始
		c.setFirstResult(2);
		c.setMaxResults(5) ;

		printUsers(c.list());
		
	}
	
	private static void printUsers(List<User> users) {
		for (User user : users) {
			System.out.println(user);
		}
	}
}