HQL查询

查询全部列

Query q = session.createQuery("from User ");  //OK
Query q = session.createQuery("select * from User ");  //不支持
Query q = session.createQuery("select a from User a");  // OK
System.out.println(q.list());

查询指定的列 【返回对象数据Object[] 】

Query q = session.createQuery("select a.name from User a");  
System.out.println(q.list());

查询指定的列, 自动封装为对象 【必须要提供带参数构造器】

Query q = session.createQuery("select new User(a.name) from User a");  
System.out.println(q.list());

条件查询: 一个条件/多个条件and or/between and/模糊查询

条件查询: 占位符
Query q = session.createQuery("from Dept d where deptName=?");
q.setString(int arg0, String arg1);
q.setParameter(int arg0, Object arg1);
System.out.println(q.list());
条件查询: 命名参数
Query q = session.createQuery("from Dept d where deptId=:myId or deptName=:name");
q.setParameter("myId", 12);
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, 20);
System.out.println(q.list());
模糊
Query q = session.createQuery("from User where name like ?");
q.setString(0, "1");
q.setParameter(0, "A%");
System.out.println(q.list());

聚合函数统计

Query q = session.createQuery("select count(*) from Dept");
Long num = (Long) q.uniqueResult();
System.out.println(num);

分组查询

//-- 统计t_employee表中,每个部门的人数
//数据库写法:SELECT dept_id,COUNT(*) FROM t_employee GROUP BY dept_id;
// HQL写法
Query q = session.createQuery("select e.dept, count(*) from Employee e group by e.dept");
System.out.println(q.list());

连接查询

//1) 内连接   【映射已经配置好了关系,关联的时候,直接写对象的属性即可】
Query q = session.createQuery("from Dept d inner join d.emps");

//2) 左外连接
Query q = session.createQuery("from Dept d left join d.emps");

//3) 右外连接
Query q = session.createQuery("from Employee e right join e.dept");

q.list();

连接查询 - 迫切连接

//1) 迫切内连接    【使用fetch, 会把右表的数据,填充到左表对象中!】
Query q = session.createQuery("from Dept d inner join fetch d.emps");
q.list();

//2) 迫切左外连接
Query q = session.createQuery("from Dept d left join fetch d.emps");
q.list();

你可能感兴趣的:(Hibernate)