Hibernate中Hql的查询

一 . Hibernate 查询语言(HQL)是一种面向对象的查询语言,类似于 SQL,但不是去对表和列进行操作,而是面向对象和它们的属性。 HQL 查询被 Hibernate 翻译为传统的 SQL 查询从而对数据库进行操作。

  1.简单的查询操作案例:

    1.1定义hibernate的主配置文件hibernate.cfg.xml

  

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
    <!-- 配置sessionFactory,表示获取连接,包含连接的四要素 
        注:hibernate 连接的四要素中的名字不能更改,必须是以下的名字
    -->
<session-factory>
    <!--方言   告诉hibernate,连接的是oracle数据库     -->
    <property name="dialect">
        org.hibernate.dialect.Oracle9Dialect
    </property>
    <property name="connection.url">
        jdbc:oracle:thin:local:1521:orcl
    </property>
    <property name="connection.username">scott</property>
    <property name="connection.password">tiger</property>
    <property name="connection.driver_class">
        oracle.jdbc.OracleDriver
    </property>
    <!-- 此标签用于是否在控制台输出sql语句  此处ture表示输出 -->
    <property name="show_sql">true</property>
    <!--此标签表示引入hiberante的映射文件 -->
    <mapping resource="cn/et/hibernate/lesson02/relation/Dept.hbm.xml" />
    <mapping resource="cn/et/hibernate/lesson02/relation/Emp.hbm.xml" />
</session-factory>

</hibernate-configuration>

  1.2 定义Hibernate的映射文件Dept.hbm.xml  ,Emp.hbm.xml 

  

<!--此映射文件为Emp表的映射文件-->
<?
xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="cn.et.hibernate.lesson02.relation.Emp" table="EMP" schema="SCOTT"> <id name="empno" type="java.lang.Short"> <column name="EMPNO" precision="4" scale="0" /> <generator class="native" /> </id> <!-- many-t-one 表示多对以的关系 Emp表对应Dept表示一对多的关系 模拟查询语句:select * from emp where deptno="其中的一列" --> <many-to-one name="dept" class="cn.et.hibernate.lesson02.relation.Dept" fetch="select"> <column name="DEPTNO" precision="3" scale="0"> <comment>所属部门编号</comment> </column> </many-to-one> <property name="ename" type="java.lang.String"> <column name="ENAME" length="10"> <comment>员工姓名</comment> </column> </property> <property name="job" type="java.lang.String"> <column name="JOB" length="9"> <comment>员工职位</comment> </column> </property> <property name="mgr" type="java.lang.Short"> <column name="MGR" precision="4" scale="0"> <comment>领导编号</comment> </column> </property> <property name="hiredate" type="java.util.Date"> <column name="HIREDATE" length="7"> <comment>雇佣日期</comment> </column> </property> <property name="sal" type="java.lang.Double"> <column name="SAL" precision="7"> <comment>月薪</comment> </column> </property> <property name="comm" type="java.lang.Double"> <column name="COMM" precision="7"> <comment>奖金</comment> </column> </property> </class> </hibernate-mapping>

  

<!--此映射文件为Dept表的映射文件-->
<?
xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="cn.et.hibernate.lesson02.relation.Dept" table="DEPT" schema="SCOTT"> <id name="deptno" type="java.lang.Short"> <column name="DEPTNO" precision="3" scale="0" /> <generator class="native" /> </id> <property name="dname" type="java.lang.String"> <column name="DNAME" length="14"> <comment>部门名称</comment> </column> </property> <property name="loc" type="java.lang.String"> <column name="LOC" length="13"> <comment>部门所在位置</comment> </column> </property> <!-- set 中的name 表示实体类中的集合名称 inverse="true" 表示控制反转的意思 --> <set name="emps" inverse="true"> <!-- key 的意思表示将要查询表的主键 当做下一个表的查询条件--> <key> <column name="DEPTNO" precision="3" scale="0"> </column> </key> <!-- 表示一对多的关系,Dept表对Emp表示一对多的关系--> <one-to-many class="cn.et.hibernate.lesson02.relation.Emp" /> </set> </class> </hibernate-mapping>

  1.3 创建Emp表 Dept表的实体类

  

//此表示Dept表的实体类
package
cn.et.hibernate.lesson02.relation; import java.util.HashSet; import java.util.Set; /** * Dept entity. @author MyEclipse Persistence Tools */ public class Dept implements java.io.Serializable { // Fields private Short deptno; private String dname; private String loc; //set集合表示不可重复的 private Set emps = new HashSet(0); // Constructors /** default constructor */ public Dept() { } /** full constructor */ public Dept(String dname, String loc, Set emps) { this.dname = dname; this.loc = loc; this.emps = emps; } // Property accessors public Short getDeptno() { return this.deptno; } public void setDeptno(Short deptno) { this.deptno = deptno; } public String getDname() { return this.dname; } public void setDname(String dname) { this.dname = dname; } public String getLoc() { return this.loc; } public void setLoc(String loc) { this.loc = loc; } public Set getEmps() { return this.emps; } public void setEmps(Set emps) { this.emps = emps; } }
//此表示Dept表的实体类
package
cn.et.hibernate.lesson02.relation; import java.util.Date; /** * Emp entity. @author MyEclipse Persistence Tools */ public class Emp implements java.io.Serializable { // Fields private Short empno; //有一个Dept对象 private Dept dept; private String ename; private String job; private Short mgr; private Date hiredate; private Double sal; private Double comm; // Constructors /** default constructor */ public Emp() { } /** full constructor */ public Emp(Dept dept, String ename, String job, Short mgr, Date hiredate, Double sal, Double comm) { this.dept = dept; this.ename = ename; this.job = job; this.mgr = mgr; this.hiredate = hiredate; this.sal = sal; this.comm = comm; } // Property accessors public Short getEmpno() { return this.empno; } public void setEmpno(Short empno) { this.empno = empno; } public Dept getDept() { return this.dept; } public void setDept(Dept dept) { this.dept = dept; } public String getEname() { return this.ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return this.job; } public void setJob(String job) { this.job = job; } public Short getMgr() { return this.mgr; } public void setMgr(Short mgr) { this.mgr = mgr; } public Date getHiredate() { return this.hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } public Double getSal() { return this.sal; } public void setSal(Double sal) { this.sal = sal; } public Double getComm() { return this.comm; } public void setComm(Double comm) { this.comm = comm; } }

  1.4 创建测试类,此测试类中有几种测试方法,注意区别

package cn.et.hibernate.lesson02.hsql;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import cn.et.hibernate.lesson02.relation.Dept;
import cn.et.hibernate.lesson02.relation.Emp;
//此测试类是通过hsql语句进行查询

public class TestHibernate {
    @Test
    //此方法是简单的查询Emp表中的所有数据,无条件限定
    public void test1(){
        //创建sessionFactory
        SessionFactory sf = new Configuration().configure("/cn/et/hibernate/lesson02/hibernate.cfg.xml").buildSessionFactory();
        Session session = sf.openSession();
        //表示产生hql语句的过程
        Query createQuery = session.createQuery("from Emp");
        //该查询语句返回的是个List集合
        List<Emp> querList = createQuery.list();
        Iterator it = querList.iterator();
        while (it.hasNext()) {
            Emp e = (Emp) it.next();
            System.out.println(e.getEname()+"   "+e.getJob());
        }
        System.out.println(querList.size());
    }
    
    @Test
    //此方法通过hql方法进行数据库的查询,通过where条件进行简单的查询
    public void hsqlTest(){
        SessionFactory sf = new Configuration().configure("/cn/et/hibernate/lesson02/hibernate.cfg.xml").buildSessionFactory();
        Session session = sf.openSession();
        //定义一条HSQL的查询语句 通过?号的方式进行传参
        //Query createQuery = session.createQuery("from Emp where ename=?");
        //设置查询参数的值,用?号传参,此处的设置参数的索引是从0开始
        //createQuery.setParameter(0, "ALLEN");
        
        //传参的第二种方式 通过冒号:进行传参
        Query createQuery = session.createQuery("from Emp where ename=:myEname");
        //设置参数,通过?号的方式进行传参
        createQuery.setParameter("myEname", "ALLEN");
        List<Emp> querList = createQuery.list();
        Iterator it = querList.iterator();
        while (it.hasNext()) {
            Emp e = (Emp) it.next();
            System.out.println(e.getEname()+"   "+e.getJob());
        }
        System.out.println(querList.size());
    }
    /*
     * 以上文Hibernate的两种传参方式
     *         ?是jdbc的传参方式,通过位置jdbc从1开始, hibernate是从0开始
     *         :是通过名称的传参方式,通过设置键值对的方式进行传参(建议使用名称进行传参)
     */
    @Test
    //此方法通过hql对象的方式进行查询,然后通过对象点的方式进行关联表的查询操作
    public void hsqlTest1(){
        SessionFactory sf = new Configuration().configure("/cn/et/hibernate/lesson02/hibernate.cfg.xml").buildSessionFactory();
        Session session = sf.openSession();
        //第一种:此处通过对象的方式进行传参(建议使用)
        Query createQuery = session.createQuery("from Dept where deptno=:myEname");
        //设置参数,通过?号的方式进行传参
        createQuery.setParameter("myEname",Short.parseShort("30"));
        List<Dept> querList = createQuery.list();
        Iterator it = querList.iterator();
        while (it.hasNext()) {
            Dept e = (Dept) it.next();
            System.out.println(e.getDname());
        }
        //打印集合的第一个元素与,通过对象点的方式,查询对映学生表中的数据有多少条
        System.out.println(querList.get(0).getEmps().size());
        
        
        /*//第二种方式 此处通过对象的方式进行传参
        Query createQuery = session.createQuery("from Emp e where e.dept.deptno=:myEname");
        //设置参数,通过?号的方式进行传参
        createQuery.setParameter("myEname",Short.parseShort("30"));
        List<Emp> querList = createQuery.list();
        Iterator it = querList.iterator();
        while (it.hasNext()) {
            Emp e = (Emp) it.next();
            System.out.println(e.getEname());
        }
        //打印集合的第一个元素与,通过对象点的方式,查询对映学生表中的数据有多少条
        System.out.println(querList.size());*/
    }
}
原文地址:https://www.cnblogs.com/xushirong/p/7057851.html