Hibernate迫切连接和普通连接的区别实例详解
Hibernate迫切连接和普通连接的区别
相关的介绍和解释在代码中已注释,大家可以参考。
packagecom.baidu.test;
importjava.util.ArrayList;
importjava.util.LinkedHashSet;
importjava.util.List;
importorg.hibernate.Query;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.hibernate.Transaction;
importorg.hibernate.cfg.Configuration;
importorg.hibernate.service.ServiceRegistry;
importorg.hibernate.service.ServiceRegistryBuilder;
importorg.junit.After;
importorg.junit.Before;
importorg.junit.Test;
importcom.baidu.leftJoin.Department;
importcom.baidu.leftJoin.Employee;
publicclassTestHQL_LeftJoin{
	privateSessionFactorysessionFactory;
	privateSessionsession;
	privateTransactiontransaction;
	@Before
	publicvoidinit(){
		Configurationconfiguration=newConfiguration().configure();
		ServiceRegistryserviceRegistry=newServiceRegistryBuilder()
		.applySettings(configuration.getProperties())
		.buildServiceRegistry();
		sessionFactory=configuration.buildSessionFactory(serviceRegistry);
		session=sessionFactory.openSession();
		transaction=session.beginTransaction();
	}
	@After
	publicvoiddestroy(){
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
	//~~~~~~~~~~~~~~~~~~~~~~~~~~下面的例子是从1对多~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	/**
*
*迫切左外连接:特点是:如果左表有不满足条件的,也返回左表不满足条件
*1.LEFTJOINFETCH关键字表示迫切左外连接检索策略.
*2.list()方法返回的集合中存放实体对象的引用,每个Department对象关联的Employee集合都被初始化,
*存放所有关联的Employee的实体对象.
*3.查询结果中可能会包含重复元素,可以通过一个HashSet来过滤重复元素
*
*去重:
*方法一:使用distinct
*Stringhql="SELECTDISTINCTdFROMDepartmentdLEFTJOINFETCHd.emps";
*Queryquery=session.createQuery(hql);
*
*Listdepts=query.list();
*System.out.println(depts.size());
*
*方法二
*Stringhql="FROMDepartmentdLEFTJOINFETCHd.emps";
*Queryquery=session.createQuery(hql);
*
*Listdepts=query.list();
*
*depts=newArrayList<>(newLinkedHashSet(depts));
*System.out.println(depts.size());
*
*for(Departmentdept:depts){
*System.out.println(dept.getName()+"--"+dept.getEmps().size());
*}
*
*
*/
	@Test
	publicvoidtestLeftJoinFetch(){
		//Stringhql="SELECTDISTINCTdFROMDepartmentdLEFTJOINFETCHd.emps";
		//Queryquery=session.createQuery(hql);
		//
		//Listdepts=query.list();
		//System.out.println(depts.size());
		//
		Stringhql="FROMDepartmentdLEFTJOINFETCHd.emps";
		Queryquery=session.createQuery(hql);
		Listdepts=query.list();
		System.out.println(depts.size());
		depts=newArrayList<>(newLinkedHashSet(depts));
		System.out.println(depts.size());
		for(Departmentdept:depts){
			System.out.println(dept.getName()+"--"+dept.getEmps().size());
		}
	}
	/**
*左外连接:
*1.LEFTJOIN关键字表示左外连接查询.
*2.list()方法返回的集合中存放的是对象数组类型
*3.根据配置文件来决定Employee集合的检索策略.
*4.如果希望list()方法返回的集合中仅包含Department对象,
*可以在HQL查询语句中使用SELECT关键字
*
*这样的语句查询的结果有重复:
*Stringhql="FROMDepartmentdLEFTJOINd.emps";
*Queryquery=session.createQuery(hql);
*
*List    
总结
以上就是本文关于Hibernate迫切连接和普通连接的区别实例详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:
浅谈hibernate急迫加载问题(多重外键关联)
Hibernate中Session增删改查操作代码详解
如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!