HIbernate多表操作(连接)

多表操作测试类

public class HQLJoinTest {
	//显示内连接
	@Test
	public void test1() {
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		String hql = "from Customer c inner join c.orders with c.id = 1";
		Query query = session.createQuery(hql);
		//结果得到一个list集合,集合里面的每一个元素是Object数组,每一个数组里面有一个Customer对象与一个Order对象
		List<Object[]> list = query.list();
		for (Object[] objects : list) {
			for (Object object : objects) {
				System.out.print(object+"\t");
			}
		}
		
		session.getTransaction().commit();
		session.close();
	}

	
	//隐式内连接
	@Test
	public void test2() {
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		//一个Order只有一个c
		String hql = "from Order o where o.c.id = 1 ";
		//一个c有好多个Order,所以c.orders.cCustomerId行不通?
		//String hql = "from Customer c where c.orders.cCustomerId = 1 ";
		Query createQuery = session.createQuery(hql);
		List list = createQuery.list();
		System.out.println(list);
		
		session.getTransaction().commit();
		session.close();
	}
	
	//迫切内连接
	//迫切内连接得到的结果是直接封装到PO类中,而内连接得到的是Object[]数组,数组中封装的是PO类对象。
	@Test
	public void test3() {
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		//使用distinct去重
		//注意:fetch不可以与单独条件的with一起使用
		String hql = "select distinct c from Customer c inner join fetch c.orders where c.id = 1 ";
		//String hql = "select distinct o from Order o inner join fetch o.c ";
		Query createQuery = session.createQuery(hql);
		List<Customer> list = createQuery.list();//集合中是from后面的对象
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		session.getTransaction().commit();
		session.close();
	}
	
	//测试外连接
	@Test
	public void test4() {
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		String hql = "from Customer c left outer join c.orders";
		Query createQuery = session.createQuery(hql);
		List<Object[]> list = createQuery.list();
		for (Object[] objects : list) {
			for (Object object : objects) {
				System.out.println(object+"\t");
			}
		}
		
		session.getTransaction().commit();
		session.close();
	}
	
	//迫切左外连接
	@Test
	public void test5() {
		Session session = HibernateUtils.openSession();		
		session.beginTransaction();
		
		// 注意:fetch不可以与单独条件的with一起使用
		String hql = "select distinct c from Customer c left outer join fetch c.orders where c.id = 1";
		Query createQuery = session.createQuery(hql);
		List<Customer> list = createQuery.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		session.getTransaction().commit();
		session.close();
	}
	
	
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值