hibernate的查询方式常见的主要分为三种: HQL, QBC(Query By Criteria)查询, 以及使用原生SQL查询
HQL查询
• HQL(Hibernate Query Language)提供了丰富灵活的查询方式,使用HQL进行查询也是Hibernate官方推荐使用的查询方式。
• HQL在语法结构上和SQL语句十分的相同,所以可以很快的上手进行使用。使用HQL需要用到Hibernate中的Query对象,该对象专门执行HQL方式的操作。
查询所有示例 session.beginTransaction(); String hql = "from User"; // from 后跟的是要查询的对象,而不是表 Query query = session.createQuery(hql); List<User> userList = query.list(); for(User user:userList){ System.out.println(user.getUserName()); } session.getTransaction().commit();
获取一个不完整的对象 session.beginTransaction(); String hql = "select userName from User"; Query query = session.createQuery(hql); List nameList = query.list(); for(Object obj:nameList){ System.out.println(obj); } session.getTransaction().commit(); // 多个属性的话,需要用object[]接收 session.beginTransaction(); String hql = "select userName,userPwd from User"; Query query = session.createQuery(hql); List nameList = query.list(); for(Object obj:nameList){ Object[] array = (Object[]) obj; // 转成object[] System.out.println("name:" + array[0]); System.out.println("pwd:" + array[1]); } session.getTransaction().commit();
统计和分组查询 session.beginTransaction(); String hql = "select count(*),max(id) from User"; Query query = session.createQuery(hql); List nameList = query.list(); for(Object obj:nameList){ Object[] array = (Object[]) obj; System.out.println("count:" + array[0]); System.out.println("max:" + array[1]); } session.getTransaction().commit();
更多写法
select distinct name from Student;
select max(age) from Student;
select count(age),age from Student group by age;
from Student order by age;
HQL占位符和分页 session.beginTransaction(); String sql ="select uname,password from User where enable=?"; Query query =session.createQuery(sql); //占位符内容 query.setBoolean(0, true); //第几个开始 query.setFirstResult(0); //显示个数 query.setMaxResults(2); List<Object[]> list = query.list(); for (Object[] user : list) { System.out.println(user[0]+"--"+user[1]); } session.getTransaction().commit();
原生SQL查询
addEntity()示例 session.beginTransaction(); String sql = "select id,username,userpwd from t_user"; // addEntity()可以告诉Hibernate你想要封装成对象的类型,然后自动为你封装 SQLQuery query = session.createSQLQuery(sql).addEntity(User.class); List<User> list = query.list(); for(User user : list){ System.out.println(user.getUserName()); } session.getTransaction().commit();
uniqueResult示例 session.beginTransaction(); String sql = "select id,username,userpwd from t_user where id = 2"; SQLQuery query = session.createSQLQuery(sql).addEntity(User.class); User user = (User) query.uniqueResult(); System.out.println(user.getUserName()); session.getTransaction().commit();