zoukankan      html  css  js  c++  java
  • Hibernate4.3 HQL查询

    HQL:Hibernate专属语言,可以跨数据库

    一、基本查询

     1 public void testQuery(){
     2         Session session = HibernateUtils.getSession();
     3         String hql = "from Person";
     4         Query query = session.createQuery(hql);
     5         List<Person> list = query.list();
     6         for(Person p : list){
     7             System.out.println(p);
     8         }
     9         HibernateUtils.close(session);
    10     }

      单个属性列查询

    1 //查询单个属性
    2         String hql = "select p.pname from Person p";
    3         Query query = session.createQuery(hql);
    4         List<String> list = query.list();

      多个属性查询

    1 //查询多列
    2         String hql = "select p.id,p.pname from Person p";
    3         Query query = session.createQuery(hql);
    4         List<Object[]> objArrList = query.list();
    5         for(Object[] objArr : objArrList){
    6             System.out.println("编号:"+objArr[0]+"   姓名:"+objArr[1]);
    7         }

    二、Hibernate分页查询

    1 Session session = HibernateUtils.getSession();
    2         String hql = "from Person";
    3         Query query = session.createQuery(hql);
    4         //设置分页查询
    5         query.setFirstResult(0);
    6         query.setMaxResults(5);
    7         List<Person> list = query.list();

    三、限定查询

    String hql = "from Person  where id = ?";
            Query query = session.createQuery(hql);
            query.setParameter(0, 5);
            List<Person> list = query.list();
    1 Session session = HibernateUtils.getSession();
    2         String hql = "from Person  where id = :id";
    3         Query query = session.createQuery(hql);
    4         query.setParameter("id", 5);
    5         List<Person> list = query.list();

    四、统计查询

    1 String hql = "select count(*) from Person p";
    2         Query query = session.createQuery(hql);
    3         Object result =  query.uniqueResult();

    五、分组统计查询

    1 String hql = "select avg(p.salary),p.pgender from Person p group by p.pgender";
    2         Query query = session.createQuery(hql);
    3         List<Object[]> objArrList = query.list();

    六、投影查询

    建立一个业务Bean,在bean提供有参的构造器来接收sql的返回值,创建出对象

    七、排序查询

    1 String hql = "from Person p order by p.salary desc";
    2         Query query = session.createQuery(hql);
    3         List<Person> list = query.list();

    八、从配置文件中设置查询,然后提取

    在 Person.hbm.xml配置文件中
    1
    <query name="getPerson"> 2 <![CDATA[ 3 from Person p where p.salary > 400 4 ]]> 5 </query>
    1 Query query = session.getNamedQuery("getPerson");
    2         List<Person> list = query.list();
  • 相关阅读:
    高阶函数 练习
    斐波那契数列(Fibonacci sequence)递归函数
    顺序循环队列的基本操作(二)
    顺序循环队列基本操作(一)
    顺序栈的基本操作
    双链表的插入删除
    头插法实现链表逆置
    带头结点单链表的基本操作
    顺序表基本操作
    实现原数组列变成行,再将每一行首尾倒置
  • 原文地址:https://www.cnblogs.com/cat-fish6/p/8674257.html
Copyright © 2011-2022 走看看