标签:
1)Get/load主键查询
//1)主键查询
// Dept dept = (Dept)session.load(Dept.class,1);
// Dept dept = (Dept)session.get(Dept.class,1);
System.out.println(dept);
结果
Hibernate: select dept0_.deptId as deptId0_0_, dept0_.deptName as deptName0_0_ from t_dept dept0_ where dept0_.deptId=? com.cx.hqlQuery.Dept@302552ec
2) 对象导航查询
//2)对象导航查询 Dept dept = (Dept)session.get(Dept.class,1); System.out.println(dept.getEmployees());
结果
Hibernate: select dept0_.deptId as deptId0_0_, dept0_.deptName as deptName0_0_ from t_dept dept0_ where dept0_.deptId=? Hibernate: select employees0_.dept_id as dept4_0_1_, employees0_.empId as empId1_, employees0_.empId as empId1_0_, employees0_.empName as empName1_0_, employees0_.salary as salary1_0_, employees0_.dept_id as dept4_1_0_ from t_employee employees0_ where employees0_.dept_id=? [com.cx.hqlQuery.Employee@7bedc48a, com.cx.hqlQuery.Employee@38afe297]
3)HQL查询
使用hql查询的时候,映射文件auto-import="true"要设置为true,如果是false,在写hql的时候,要指定类的全名。
//3)HQL查询
//a查询全部列
Query q = session.createQuery("from Employee");
System.out.println(q.list());
//b查询指定列
Query q = session.createQuery("select d.deptId , d.deptName from Dept d");
System.out.println(q.list());
//c查询指定列,自动封装为对象(必须提供有参数的构造器)
Query q = session.createQuery("select new Dept(d.deptId,d.deptName) from Dept d");
System.out.println(((Dept)q.list().get(0)).getDeptName());
//d 条件查询
//条件查询-占位符
Query q = session.createQuery("from Dept d where deptName = ?");
// q.setString(0,"综合部");
q.setParameter(0,"综合部");
System.out.println(q.list());
//条件查询,命名参数
Query q = session.createQuery("from Dept d where deptId=:myId or deptName=:name");
q.setParameter("myId",1);
q.setParameter("name","综合部");
System.out.println(q.list());
//范围
Query q = session.createQuery("from Dept d where deptId between ? and ?");
q.setParameter(0,1);
q.setParameter(1,6);
System.out.println(q.list());
//模糊查询
Query q = session.createQuery("from Dept d where deptName like ?");
q.setString(0,"%部%");
System.out.println(q.list());
//e.聚合函数统计
Query q = session.createQuery("select count (*) from Dept");
Long num = (Long)q.uniqueResult();
System.out.println(num);
//分组查询,统计每个部门的人数
Query q = session.createQuery("select e.dept , count(*) from Employee e group by e.dept");
System.out.println(q.list());
标签:
原文地址:http://www.cnblogs.com/cxspace/p/5737793.html