1.使用hql语句检索出Student表中的所有列
//核心代码 @Test public void oneTest() { Query query=session.createQuery("form Student"); List<Student> list=query.list(); for(Student item:list) { System.out.println(item.getName()); } }
2.使用hql语句语句检索出部分列
//核心代码 @Test public void twoTest() { Query query=session.createQuery("select name from Student"); List<String> list=query.list(); for(String item:list) { System.out.println(item); } }
3.使用hql语句检索出多列
//核心代码 @Test public void threeTest() { Query query=session.createQuery("select name,age from Student"); List<Object[]> list=query.list(); for(Object[] item : list) { System.out.println(item[0]+" "+item[1]); } }
4.投影出多列,有构造植入,返回强类型
//核心代码 @Test public void fourTest() { Query query=session.createQuery("select Student(id,name,age) from Student");
//Student(id,name,age)和实体类带参构造顺序相同 List<Student> list=query.list(); for(Student item:list) { System.out.println(item.getName()); } }
5.带条件查询,匿名占位符
//核心代码 @Test public void fiveTest() { Query query=session.createQuery("select Student from Student where name=?"); query.setParameter(0,"王小三"); List<Student> list=query.list(); for(Student item:list) { System.out.println(item.getName()); } }
6.带条件查询,名称占位符
//核心代码 @Test public void SixTest() { Query query = session.createQuery("select Student from Student where stu.sname=:name"); query.setParameter("name", "王小四"); List<Student> list=query.list(); for (Student item : list) { System.out.println(item.getSid()); } }
7.动态查询,需要新建一个工具类,用到几个属性就封装几个属性
public class StudentCondition { private String name; private Integer age; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
//测试类核心代码 StudentCondition condition=new StudentCondition(); condition.setAge(25); condition.setName(null); StringBuilder sb=new StringBuilder(); sb.append("from Student where 1=1 "); Student stu=new Student(); if(condition.getAge()!=null) { sb.append(" and sage=:sage"); stu.setSage(condition.getAge()); } if(condition.getName()!=null) { sb.append(" and sname=:sname"); stu.setSname(condition.getName()); } Query query = session.createQuery(sb.toString()); query.setProperties(stu); List<Student> list=query.list(); for (Student item : list) { System.out.println(item.getSname()); }
//投影出年龄25岁的学生信息 }
8.分页查询数据
@Test public void nineTest() { String sql="from Student"; Query query = session.createQuery(sql); Integer pageIndex=1; Integer pageSize=2; query.setFirstResult((pageIndex-1)*pageSize); query.setMaxResults(pageSize); List<Student> list = query.list(); for (Student student : list) { System.out.println(student); }