---
title: "Hibernate part 13：批量检索策略"
author: "mvplee"
date: "2015-03-08T20:10:21Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-part-13"
draft: false
lastmod: "2015-08-30T22:28:41Z"
id: 2190470
url: "https://mvplee.iteye.com/blog/2190470"
---

从Customer到Order，配置在&lt;set&gt;标签中，batch-size表示一次查询几个客户的订单，而不查询的订单数量，配置为2，表示一次查询两个客户的订单数量

```
<hibernate-mapping>
	<class name="rock.lee.bean.Customer" table="customer" catalog="test" >
		<id name="id" column="id" type="int">
			<generator class="native"></generator>
		</id>
		<set name="orders" cascade="save-update,delete,delete-orphan" inverse="true"  fetch="select" lazy="true"  batch-size="2">
			<!-- customer表order是中所生成的外键列 -->
			<key column="customer_id"></key>
			<one-to-many class="rock.lee.bean.Order" />
		</set>
		<property name="name" column="name" type="java.lang.String"></property>
		<property name="city" column="city" type="java.lang.String"></property>
	</class>
</hibernate-mapping>
```

 查询所有的Customer并且获得Order集合的大小

```
	@Test
	public void test05() {
		Session session = HibernateUtils.openSession();
		Transaction transaction = session.beginTransaction();
		
		List<Customer> list = session.createQuery(" from Customer").list();
		for (Customer c : list) {
			System.out.println(c.getOrders().size());
		}
		
		transaction.commit();
		session.close();
	}
```

 SQL：

```
Hibernate: 
    select
        customer0_.id as id0_,
        customer0_.name as name0_,
        customer0_.city as city0_ 
    from
        test.customer customer0_
Hibernate: 
    select
        orders0_.customer_id as customer4_0_1_,
        orders0_.id as id1_,
        orders0_.id as id1_0_,
        orders0_.address as address1_0_,
        orders0_.money as money1_0_,
        orders0_.customer_id as customer4_1_0_ 
    from
        test.orders orders0_ 
    where
        orders0_.customer_id in (
            ?, ?
        )
```

 通过in条件查询order

 

从Orders到Customer配置在Customer.hbm.xml中的&lt;class&gt;标签中batch-size，一次查询几个客户

```
<hibernate-mapping>
      <class name="rock.lee.bean.Customer" table="customer" catalog="test" batch-size="2">
</hibernate-mapping>
```

 

检索策略的比较  
![](http://dl2.iteye.com/upload/attachment/0106/4775/7136aabb-9e9b-3f27-9613-39c1c73f71e1.png)