码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate学习-11-几种查询详解

时间:2016-08-04 19:10:17      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

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());

 

Hibernate学习-11-几种查询详解

标签:

原文地址:http://www.cnblogs.com/cxspace/p/5737793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!