Hibernate批量查询

批量查询

l  当客户 关联查询 订单,给每一个客户生产一个select语句查询订单。批量查询使用in语句减少查询订单语句个数。

       默认:select * from t_order wherecustomer_id = ?

       批量:select * from t_order wherecustomer_id in (?,?,?,?)

5表示括号中?个数。

Hibernate批量查询_第1张图片

@Test
	public void demo06() {
		//批量查询
		Session session = factory.openSession();
		session.beginTransaction();
		
		//1 查询所有客户
		List allCustomer = session.createQuery("from Customer").list();
		
		//2遍历
		for (Customer customer : allCustomer) {
			System.out.println(customer.getCname());
			System.out.println(customer.getOrderSet().size());
		}
		
		
		session.getTransaction().commit();
		session.close();
	}

批量加载
set
batch-size: 决定一次加载几个对象的集合数据. in 条件加载多个用户的订单.

case:
package com.itheima.b_lazy;

import java.util.List;

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

import com.itheima.domain.Customer;
import com.itheima.domain.Order;
import com.itheima.utils.HibernateUtils;
//批量策略
public class Demo4 {
	@SuppressWarnings("unchecked")
	@Test
	//查询所有客户
	//遍历客户,打印客户下的订单信息
	public void fun1(){
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		//------------------------------------------------
		List list = session.createQuery("from Customer").list();
		
		for(Customer c:list){
			System.out.println(c.getOrders().size());
		}
		//------------------------------------------------
		session.getTransaction().commit();
		session.close(); // 游离状态
	}
	
	
	@Test
	//fetch: select
	//lazy: proxy
	// Customer lazy:false
	public void fun2(){
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		//------------------------------------------------
		Order o = (Order) session.get(Order.class, 2);
		
		System.out.println(o.getCustomer().getName());
		
		//------------------------------------------------
		session.getTransaction().commit();
		session.close(); // 游离状态
	}
	@Test
	//fetch: select
	//lazy: proxy
	// Customer lazy:true
	public void fun3(){
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		//------------------------------------------------
		Order o = (Order) session.get(Order.class, 2);
		
		System.out.println(o.getCustomer().getName());
		
		//------------------------------------------------
		session.getTransaction().commit();
		session.close(); // 游离状态
	}
	
	@Test
	//fetch: join
	//lazy: proxy|false
	public void fun4(){
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		//------------------------------------------------
		Order o = (Order) session.get(Order.class, 2);
		
		System.out.println(o.getCustomer().getName());
		
		//------------------------------------------------
		session.getTransaction().commit();
		session.close(); // 游离状态
	}
}




你可能感兴趣的:(JavaEE,hibernate)