三套查询之Criteria查询
完全面向对象的,不需要写任可查询语句.
1.查询所有的学生
1 //1.查询所有的学生
2 @Test
3 public void test1(){
4 Criteria criteria = session.createCriteria(Student.class);
5 List<Student> list = criteria.list();
6 for (Student student : list) {
7 System.out.println(student.getId()+student.getName());
8 }
9
10 Criteria criteria2 = session.createCriteria("com.rong.entity.group.Student");
11 List<Student> list2 = criteria2.list();
12 for (Student student : list2) {
13 System.out.println(student.getId()+student.getName());
14 }
15 }
2.添加查询条件
add(Criterion criterion) : 添加查询条件.
Criterion : 代表一个查询条件.
Restrictions工具类,专门负责生成查询条件对象,它把where部分都改成了静态方法。
sqlRestriction(String sql) : 生成查询条件的万能方法.
Property工具类,专门负责生成查询条件对象.
Propery.forName("属性名").xxx()
1 //2.添加查询条件
2 @Test
3 public void test2(){
4 //1.添加一个
5 Criteria criteria = session.createCriteria(Student.class);
6 criteria=criteria.add(Restrictions.like("name", "%ab%"));
7 List<Student> list = criteria.list();
8 for (Student student : list) {
9 System.out.println(student.getId()+student.getName());
10 }
11 //2.添加多个
12 Criteria criteria2 = session.createCriteria(Student.class);
13 criteria2.add(Restrictions.like("name", "%a%"));
14 criteria2.add(Restrictions.between("java", 60, 100));
15 List<Student> list2 = criteria2.list();
16 for (Student student : list2) {
17 System.out.println(student.getId()+student.getName());
18 }
19 System.out.println("===================================");
20 Criteria criteria3 = session.createCriteria(Student.class);
21 criteria3.add(Property.forName("name").like("%p%"));
22 criteria3.add(Property.forName("math").between(85, 100));
23 List<Student> list3 = criteria3.list();
24 for (Student student : list3) {
25 System.out.println(student.getId()+student.getName()
26 +student.getMath());
27 }
28 }