HQL查询
1.分页查询
Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { NativeQueryquery = session.createQuery("from Student", Student.class); query.setFirstResult(2);//读取数据的起始位置 query.setMaxResults(2);//每次最多读取多少条数据 List list = query.list(); System.out.println(list); transaction.commit(); } catch (Exception e) { // TODO: handle exception if (transaction!=null) { transaction.rollback(); } }
2.排序查询
Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { //from 持久化类 order by 成员变量属性名 asc/desc Queryquery = session.createQuery("from Person order by age desc", Person.class); List list = query.list(); System.out.println(list); transaction.commit(); } catch (Exception e) { // TODO: handle exception if (transaction != null) { transaction.rollback(); } }
3.聚合函数查询
//sum和count结果类型都是Long 结果类型是Long,跟所求列的类型无关 //max和min结果类型和所求列的类型一致 结果类型跟所求的列的类型有关 //avg结果类型是Double 跟所求的列的类型无关 Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { //Queryquery = session.createQuery("select count(*) from Person", Long.class); //Query query = session.createQuery("select sum(age) from Person", Long.class); //Query query = session.createQuery("select max(age) from Person", Integer.class); //Query query = session.createQuery("select min(age) from Person", Integer.class); Query query = session.createQuery("select avg(age) from Person", Double.class); System.out.println(query.uniqueResult()); transaction.commit(); } catch (Exception e) { // TODO: handle exception if (transaction != null) { transaction.rollback(); } }
4.映射查询
//投影查询://需求:前面查询的都是查询所有列。表示扫描整个表。//实际情况中,可能只关注表中的其中几个列,并不是所有。 如果这种情况再去扫描整个表查数据,效率低下。
//1.查询Person类中的名称列name Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { //name 是属性名 Queryquery = session.createQuery("select name from Person", String.class); System.out.println(query.list()); transaction.commit(); } catch (Exception e) { // TODO: handle exception if (transaction != null) { transaction.rollback(); } }
//2.查询Person类中的名称列name,address,查询多个列,返回结果类型是Object[]类型 Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { Query
//3.查询Person类中的名称列name,address 优化:返回值是指定的实体类类型Person(必须具有对应的有参构造方法) 无参的构造方法依然要存在 Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { Queryquery = session.createQuery("select new Person(name,sex) from Person", Person.class); List list = query.list(); System.out.println(list); transaction.commit(); } catch (Exception e) { // TODO: handle exception if (transaction != null) { transaction.rollback(); } }