hibernate系列十五:hql连接查询,查询性能优化,hql批量增删改

一 hql连接查询

和SQL查询一样,HQL也支持各种各样的连接查询,如内连接、外连接。我们知道在SQL中可通过join子句实现多表之间的连接查询。HQL同样提供了连接查询机制,还允许显式指定迫切内连接和迫切左外连接。HQL提供的连接方式如表1所示。

连接类型 HQL语法 适用范围
内连接 inner join或 join

适用于有关联关系

迫切内连接 inner join fetch或 join fetch

的持久化类,并且在

左外连接 left outer join或 left join

映射文件中对这种关

迫切左外连接 left outer join fetch或 left join fetch 联关系做了映射
右外连接 right outer join或 right join  
迫切连接是指在指定连接方式时不仅指定了连接查询方式,而且显式地指定了关联级别的查询策略。Hibernate使用fetch关键字实现,fetch关键字表明“左边”对象用于与“右边”对象关联的属性会立即被初始化。

案例一,多对一关联,无迫切连接

package com.obtk.test2;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.EmployeeEntity;
import com.obtk.utils.HibernateUtil;

public class TestJoin01 {
	public static void main(String[] args) {
		Session session=null;
		String hql="from EmployeeEntity e inner join e.dept d " +
				" where e.gender=? and d.deptName=? ";
		try {
			session=HibernateUtil.getSession();
			Query qy=session.createQuery(hql);
			qy.setParameter(0, "男");
			qy.setParameter(1, "人事部");
			List<Object[]> objList=qy.list();
			EmployeeEntity theEmp=null;
			DeptEntity dept=null;
			for(Object[] theArr :objList){
				theEmp=(EmployeeEntity)theArr[0];
				dept=(DeptEntity)theArr[1];
				System.out.println(theEmp.getEmpName()+","+theEmp.getGender()
						+","+dept.getDeptName());
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession();
		}
	}
}
案例二   多对一关联,有迫切连接(注意fetch关键字)
package com.obtk.test2;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.EmployeeEntity;
import com.obtk.utils.HibernateUtil;

public class TestFetchJoin01 {
	public static void main(String[] args) {
		Session session=null;
		String hql="from EmployeeEntity e inner join fetch e.dept d " +
				" where e.gender=? and d.deptName=? ";
		try {
			session=HibernateUtil.getSession();
			Que
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御前两把刀刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值