public class TestHibernate { Session session; Transaction tx; @After public void afterTest(){ tx.commit(); HibernateUtil.closeSession(); } @Before public void initDate(){ session=HibernateUtil.getSession(); tx = session.beginTransaction(); } /** * HQL检索所有Student表中的学生姓名 * List<Student> * */ @Test public void selectTest(){ Query query = session.createQuery("from Student"); List<Student> list = query.list(); for (Student item : list) { System.out.println(item.getName()); } } /** * 检索Student表中一列 * List<String> * */ @Test public void selectOnTest(){ Query query = session.createQuery("select name from Student"); List<String> list = query.list(); for (String item : list) { System.out.println(item); } } /** * 检索Student表中多个列 * List<Object[]> */ @Test public void selectSomeTest1(){ 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]); } } /** * 检索Student表中多个列,有构造植入,返回的是强类型对象 * */ @Test public void selectSomeTest2(){ Query query = session.createQuery("select new Student(age,name,sid) from Student"); List<Student> list = query.list(); for (Student item : list) { System.out.println("ID:"+item.getSid()+" 姓名:"+item.getName()+" 年龄:"+item.getAge()); } } /** * 匿名占位符 查找名称是 小明 的学生 * */ @Test public void anonymousTest(){ Query query = session.createQuery(" from Student where name=?"); query.setParameter(0, "小明"); List<Student> list = query.list(); for (Student item : list) { System.out.println(item.getName()); } } /** * 名称占位符 查找名称是 小明 的学生 * */ @Test public void nameTest(){ Query query = session.createQuery("from Student where name=:name"); query.setParameter("name","小明"); List<Student> list = query.list(); for (Student item : list) { System.out.println(item.getName()); } } /** * 绑定命名参数于一个对象的属性值 姓名是 小明 的学生 * 名称占位符name必须和实体类里的一致 */ @Test public void bindNameTest(){ StudentCondition stu=new StudentCondition(); stu.setName("小明"); Query query = session.createQuery("from Student where name=:name"); query.setProperties(stu); List<Student> list = query.list(); for (Student item : list) { System.out.println(item.getName()); } } /** * 动态查询 * */ @Test public void dynamicTest(){ StudentCondition stu=new StudentCondition(); stu.setName("小明"); stu.setAge(17); StringBuilder sb=new StringBuilder(); sb.append("from Student where 1=1"); Student stu1=new Student(); if (stu.getName()!=null) { sb.append(" and name=:name "); stu1.setName(stu.getName()); } if (stu.getAge()!=null) { sb.append(" and age=:age "); stu1.setAge(stu.getAge()); } Query query = session.createQuery(sb.toString()); query.setProperties(stu); List<Student> list = query.list(); for (Student item : list) { System.out.println(item.getName()); } } }