HQL多表查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HQL多表查询相关的知识,希望对你有一定的参考价值。
1. 多表的查询进来使用HQL语句进行查询,HQL语句和SQL语句的查询语法比较类似。 * 内连接查询 * 显示内连接 * select * from customers c inner join orders o on c.cid = o.cno; * 隐式内连接 * select * from customers c,orders o where c.cid = o.cno; * 外连接查询 * 左外连接 * select * from customers c left join orders o on c.cid = o.cno; * 右外连接 * select * from customers c right join orders o on c.cid = o.cno;
2. HQL的多表查询 * 迫切和非迫切: * 非迫切返回结果是Object[] * 迫切连接返回的结果是对象,把客户的信息封装到客户的对象中,把订单的信息封装到客户的Set集合中。
Set集合解决重复问题/** * HQL多表查询 * @author bamaw * */ public class Demo5 { /** * 查询客户,客户和联系人有关联 * select * from cst_customer c,cst_linkman l where c.id = l.id; * 有两个问题:1.数据的重复问题 2.数据没有封装到对象当中 */ @Test public void run1() { Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); //内连接查询 Query query = session.createQuery("from Customer c inner join c.linkmans"); //返回的是数组 List<Object[]> list = query.list(); for (Object[] objects : list) { System.out.println(Arrays.toString(objects)); } } /** * 将数据封装到对象中 * 提供关键字:使用fetch 迫切连接 */ @Test public void run2() { Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); //内连接查询 Query query = session.createQuery("from Customer c inner join fetch c.linkmans"); //返回的是对象 List<Customer> list = query.list(); for (Customer customer : list) { System.out.println(customer); } } /** * 解决重复问题 */ @Test public void run3() { Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); //内连接 Query query = session.createQuery("from Customer c inner join fetch c.linkmans"); //返回对象 List<Customer> list = query.list(); //解决重复问题,编程中都是用set集合来使用 --因为不可重复 Set<Customer> set = new HashSet<Customer>(list); for (Customer customer : set) { System.out.println(customer); } } /** * 左外连接查询 */ @Test public void run4() { Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); Query query = session.createQuery("from Customer c left join fetch c.linkmans"); List<Customer> list = query.list(); //解决重复问题 Set<Customer> set = new HashSet<Customer>(list); for (Customer customer : set) { System.out.println(customer); } } }
以上是关于HQL多表查询的主要内容,如果未能解决你的问题,请参考以下文章