Hibernateday06 HQL(Hibernate Query Language)

HQL(hibernate query language)   SQL(stander query language)
Hibernate的标准开发:O-->R--->M--->调用Hibernate的API
  核心API: Configuration-->SessionFactory-->Session-->Transaction
                                              |-->Query
   Session内部封装Connection,提供的CRUD依赖于主键
   进行非主键的查询:Query
     Query query=session.createQuery(HQL);
查询employee中的所有数据
SQL:  select * from employee(表名);
HQL:  from Employee(类名);
      根据面向对象的思想,一张表就是一个类,表和类在映射文件中对应,所以from后面是类名而不是表名。因为通过映射文件,表当中的一行数据hibernate会自动封装成对应的对象,所以HQL无须select *

查询employee表中名字叫calm的员工
SQL: select * from employee where ename='calm';
HQL: from Employee as e where e.ename='calm'
     建议:在使用HQL执行条件查询时,要为类提供别名

HQL特点
   1.类似于SQL
   2.from 类名
   3.可以有也可以没有select
   4.在进行条件查询的时候要为类取别名  别名.属性名

  查询集合: query.list();
  单独对象:query.uninqueResult()

HQL 的基础开发
  1.查询工资为300到600的员工
     SQL:关键字between ....and /not between ...and
     SQL: select * from t_employee where t_salary between 300 and 600;
     HQL: from Employee as e where e.salary between 300 and 600;
  2.查询工资为100,300,600的员工
     SQL:关键字 in /not in
  3.查询工资为200并且名字叫bobs
     SQL:关键字 and/ or not
  4.查询以xiao开头的名字
     sql:关键字 like 'xiao%'
  5.查询没有工资的员工
     SQL:关键字 is null/ is not null
     select * from t_employee where t_salary is null;
     sql不能写等于null 但是hibernate可以写等于null


HQL的投射(投影)查询 Project查询,在HQL中加入了select关键字的查询
   HQL from Employee --》每一行封装成一个Employee对象(通过映射文件)
       List<Employee> emps=query.list()
   HQL hql=select e.name,e.salary from Employee as e;
       Query query=session.createQuery(hql);
         没有返回一整行的数据无法封装成Employee,hibernate会将需要获得的数据用Object[]封装
        List<Object[]> emps=query.list();
        如果查询的是一个结果,hibernate通过query.list()封装成一个List<Object>对象。
 聚合函数  sum(),max(),min(),avg(),count()
 HQL 也可以使用聚合函数
    sql:select max(t_salary),min(t_salary) from employee;
    Hql:select e.dept.id, max(e.salary),min(e.salary),avg(e.salary)
        from Employee as e group by e.dept.id;

平均工资大于300的部门的平均工资和最大工资
    select e.dept.id, max(e.salary),avg(e.salary)
    from Employee as e group by e.dept.id having avg(e.salary)>300;

隐式多表连接:通过关系属性的多表连接
    缺点:可能有多表连接,发送多条sql语句从而降低了系统效率
 查询bobs所在的部门
  from Dept as d where d.emps.name='bobs'; hibernate3.2版本之前可以使用
  from Dept as d join fetch d.emps as e where e.name='bobs'; hibernate3.2版本之后
   如果hql中加入了join关键字,hibernate不能自动将一行数据封装成一个对象,必须加入关键字fetch
 
  使用隐士对表连接的时候注意关系属性的类型。
    没有雇员的部门 在hql当中判断集合是否为null可以使用is empty
     from Dept as d where d.emps is empty

显示多表连接:通过join关键字实现多表查询,通过一条sql语句就能完成多表查询、
 等值连接 inner join(Oracle9i可以省略)
   SQL:select e.*,d.* from g_employee e,g_dept d where e.d_id=d.t_id;
        select e.*,d.* from g_employee e inner join g_dept d on e.d_id=d.t_id;
   HQL:from Employee as e inner join e.dept
      因为加入了join关键词,不能封装成对象,每一行数据由Employee和Dept对象组成
        List<Object[]> emps=query.list();
     from Dept as d inner join fetch d.emps;
        List<Dept> depts=query.list();
  结果会有重复数据
    Set:去重,不能保留插入数据的顺序
    List:保留数据的顺序,不能去重
    LinkedSet:可以保留顺序,同时可以过滤重复
    List <Dept> depts=query.list();
    LinkedHashSet<Dept> deptsList=new LinkedHashSet<Dept>(depts);

驱动表 left outer join 匹配表 (左外连接,保留左边表的完整性)
    from Employee as e left outer join fetch e.dept

匹配表 right outer join 驱动表(右外连接,保留右边表的完整性)
   注意:右外连接hibernate不提供fetch关键词

全连接 full join  hibernate不支持full join

hibernate的分页
  Oracle:rownum
  Mysql:limit
  Query query=session.createQuery("from Employee");
    query.setFirstResult(0);//开始显示的记录,从0开始
    query.setMaxResult(3);//设置每页的记录数
    query.list();

Bulk update HQL提供的修改和删除的方法
   Query 对象实现对数据的 修改和删除
   SQL:update g_employee set name=xxx  where xxx;
   String hql="update Employee as e set e.name='xxxx' where e.id=1 ";//修改
   SLQ :delete from g_employee where t_id=1;
   HQL hql="delete Employee as e where e.id=1 ";//删除
 query对象的修改和删除与Session提供的delete(),和update()的区别
   1.Bulk update效率高
   2.Bulk update不会涉及缓存
   3.Bulk update不会涉及级联
   4.Bulk update不更新乐观锁

 

1.提供实体类Dept.java和Employee.java

package com.jsu.hb.pojo;

import java.util.HashSet;
import java.util.Set;

public class Dept {
	private Integer id;
	private String dname;
	private String dno;
	private Set<Employee> emps = new HashSet<Employee>();
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getDno() {
		return dno;
	}
	public void setDno(String dno) {
		this.dno = dno;
	}
	public Set<Employee> getEmps() {
		return emps;
	}
	public void setEmps(Set<Employee> emps) {
		this.emps = emps;
	}
	
}

 Employee.java

package com.jsu.hb.pojo;

import java.util.Date;

public class Employee {
	private Integer id;
	private String name;
	private Date birthday;
	private String email;
	private double salary;
	private Dept dept;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public Dept getDept() {
		return dept;
	}
	public void setDept(Dept dept) {
		this.dept = dept;
	}
	
}

 2.建表

create  table g_dept(
	t_id integer primary key,
	t_dname varchar2(20),
	t_dno varchar2(20)
)

create table g_employee(
	t_id integer primary key,
	t_name varchar2(25),
	t_birthday date,
	t_salary number(12,2),
	t_email varchar2(50),
	d_id integer references g_dept(t_id)
)

insert into g_dept(t_id,t_dname,t_dno) values (1,'dev','001');
insert into g_dept(t_id,t_dname,t_dno) values (2,'train','002');
insert into g_dept(t_id,t_dname,t_dno) values (3,'market','003');
insert into g_dept(t_id,t_dname,t_dno) values (4,'game','004');

insert into g_employee(t_id,t_name,t_birthday,t_email,t_salary,d_id) 
values (1,'bobs',to_date('2012-1-11','yyyy-mm-dd'),'bobs@b',100.0,1);
insert into g_employee(t_id,t_name,t_birthday,t_email,t_salary,d_id)
values (2,'scott',to_date('2010-10-11','yyyy-mm-dd'),'scott@b',300.0,1);
insert into g_employee(t_id,t_name,t_birthday,t_email,t_salary,d_id)
values (3,'tiger',to_date('2008-2-11','yyyy-mm-dd'),'tiger@b',400.0,2);
insert into g_employee(t_id,t_name,t_birthday,t_email,t_salary,d_id)
values (4,'lucy',to_date('2009-3-11','yyyy-mm-dd'),'lucy@b',600.0,2);
insert into g_employee(t_id,t_name,t_birthday,t_email,t_salary,d_id)
values (5,'lily',to_date('2012-4-11','yyyy-mm-dd'),'lily@b',1000.0,3);
insert into g_employee(t_id,t_name,t_birthday,t_email,t_salary,d_id)
values (6,'tom',to_date('2001-10-11','yyyy-mm-dd'),'tom@b',700.0,3);
insert into g_employee(t_id,t_name,t_birthday,t_email,t_salary,d_id)
values (7,'black',to_date('2001-10-11','yyyy-mm-dd'),'black@b',200.0,null);

commit

 3.提供映射文件query.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping  package="com.jsu.hb.pojo">
	<class name="Dept" table="g_dept">
		<id name="id" column="t_id">
			<generator class="increment"></generator>
		</id>
		<property name="dname" column="t_dname"></property>
		<property name="dno" column="t_dno"></property>
		<!-- 关系属性 -->
		<set name="emps" cascade="all" inverse="true">
			<key column="d_id"></key>
			<one-to-many class="Employee"></one-to-many>
		</set>
	</class>
	<class name="Employee" table="g_employee">
		<id name="id" column="t_id">
			<generator class="increment"></generator>
		</id>
		<property name="name" column="t_name"></property>
		<property name="birthday" column="t_birthday" type="java.util.Date"></property>
		<property name="email" column="t_email"></property>
		<property name="salary" column="t_salary"></property>
		<!-- 双向关系是添加关系属性 -->
	   <many-to-one name="dept" class="Dept" cascade="save-update" column="d_id"></many-to-one>
	</class>
</hibernate-mapping>

 4.在hibernate.cfg.xml中对映射文件进行注册

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory> 
		<!-- show_sql:是否显示hibernate执行的SQL语句,默认为false -->
		<property name="show_sql">true</property>
		<!-- show_sql:是否显示hibernate执行格式化输出的SQL语句,默认为false -->
		<property name="format_sql">true</property>
		<!-- 配置与数据库连接的参数 -->
		<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:oracle</property>
		<property name="connection.username">scott</property>
		<property name="connection.password">tiger</property>
		<!-- 2.自身属性相关的配置
			dialect:方言
			hibernate根据dialect的配置进行特定数据性能方面的调优
		 -->
		<property name="dialect">org.hibernate.dialect.Oracle9iDialect</property>
		<mapping resource="com/jsu/hb/pojo/query.hbm.xml"></mapping>
	</session-factory>
</hibernate-configuration>

 5.提供工具类HibernateUtil.java

 

package com.jsu.hb.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sf;
	private static ThreadLocal<Session> tl= new ThreadLocal<Session>();
	static{
		try{
				Configuration cfg = new Configuration();
				cfg.configure();
				sf=cfg.buildSessionFactory();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static Session openSession(){
		return sf.openSession();
	}
	public static Session getCurrentSession(){
		Session session = tl.get();//先从储存的线程中查找
		if(session==null){
			session=openSession();
			tl.set(session);
			return session;
		}
		return session;
	}
}

 6.提供测试类TestQuery.java

package com.jsu.hb.test;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.jsu.hb.pojo.Dept;
import com.jsu.hb.pojo.Employee;
import com.jsu.hb.util.HibernateUtil;

public class TestQuery {
	//hql查找所有
	@Test
	public void queryAll(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Employee";
		Query query = session.createQuery(hql);
		List<Employee> emps = query.list();
		for(Employee e: emps){
			System.out.println(e.getName());
		}
		tx.commit();
	}
	@Test
	public void queryByName(){
		String name="tom";
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Employee as e where e.name=?";
		Query query = session.createQuery(hql);
		query.setString(0, "tom");// 为占位符赋值,从0开始
		Employee e =(Employee)query.uniqueResult();// 返回单个对象
		System.out.println(e.getName()+" : "+e.getEmail()+" : "+e.getBirthday()+" : "+e.getSalary());
		tx.commit();
	}
	@Test
	public void testNull(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Employee as e where e.dept.id=null";
		Query query = session.createQuery(hql);
		Employee e =(Employee)query.uniqueResult();
		System.out.println(e.getName());
		tx.commit();
	}
	@Test
	public void testLike(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Employee as e where e.name like'xiao%'";
		Query query = session.createQuery(hql);
		Employee e =(Employee)query.uniqueResult();
		System.out.println(e.getName());
		tx.commit();
	}
	@Test
	public void testAggregation(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "select e.dept.id,max(e.salary),avg(e.salary),min(salary) "+
				"from Employee as e group by e.dept.id having avg(e.salary)>300";
		Query query = session.createQuery(hql);
		List<Object[]> emps = query.list();
		for(Object[] obj:emps){
			System.out.println(" 最大工资为:"+obj[0]+" 平均工资为: "+obj[1]+" 最小工资为: "+obj[2]);
		}
	}
	@Test
	public void testHiddenMT(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Dept as d join fetch d.emps as e where e.name='bobs'";
		Query query = session.createQuery(hql);
		Dept d = (Dept)query.uniqueResult();
		System.out.println("部门名称:"+d.getDname());
		tx.commit();
	}
	@Test
	public void testEqualsValueLinked(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Dept as d inner join fetch d.emps";
		Query query = session.createQuery(hql);
		List<Dept> depts = query.list();
		LinkedHashSet<Dept> deptSet = new LinkedHashSet<Dept>(depts);
		for(Dept d:deptSet){
			System.out.println(d.getDname());
		}
	}
	@Test
	public void testLinked(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Employee as e left outer join fetch e.dept";
		Query query = session.createQuery(hql);
		List<Employee> emps = query.list();
		LinkedHashSet<Employee> deptSet = new LinkedHashSet<Employee>(emps);
		for(Employee e :deptSet){
			System.out.println(e.getName());
		}
	}
	
	public void testQuery() {
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		// 开发dev部门的所有员工
		String hql = "from Employee as e where e.dept.dname='dev'";
		Query query = session.createQuery(hql);
		/* 每个员工的部门名称 */

		List<Employee> emps = query.list();
		for (Employee e : emps) {
			System.out.println(e.getName() + " : " + e.getDept().getDname());
		}
		tx.commit();

	}

	public void testC() {
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Dept as d where d.emps.name='bobs' ";
		String hql1 = "from Dept as d join fetch d.emps as e where e.name='bobs'";
		String hql2 = "from Dept as d where d.emps is empty";// 不用迭代集合
		Query query = session.createQuery(hql2);
		Dept d = (Dept) query.uniqueResult();
		System.out.println(d.getDname());
		tx.commit();
	}


	public void queryDept() {
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql1 = "from Dept as d inner join fetch d.emps";
		Query query = session.createQuery(hql1);
		List<Dept> depts = query.list();
		LinkedHashSet<Dept> depts1=new LinkedHashSet<Dept>(depts);
		for (Dept d : depts1) {
			Set<Employee> emps = d.getEmps();
			for (Employee e : emps) {
				System.out.println(d.getDname() + "  " + e.getName());
			}
		}
		tx.commit();
	}
	
	//hibernate分页
	@Test
	public void testPage(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "from Employee";
		Query query = session.createQuery(hql);
		query.setFirstResult(0);
		query.setMaxResults(3);
		List<Employee> emps =query.list();
		System.out.println(emps.size());
		tx.commit();
	}
	//修改
	@Test
	public void testUpdate(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "update Employee as e set e.name='haoren' where e.id=1";
		Query query = session.createQuery(hql);
		query.executeUpdate();
		tx.commit();
	}
	//删除
	@Test
	public void testBulk(){
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		String hql = "delete Employee as e where t_id=8";
		Query query = session.createQuery(hql);
		query.executeUpdate();
		tx.commit();
	}
}
 

 

你可能感兴趣的:(Hibernate)