Hibernate part 13:批量检索策略

 

 

 从Customer到Order,配置在<set>标签中

<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

 

同Order到Customer配置在<class>标签中

<hibernate-mapping>
	<class name="rock.lee.bean.Order" table="orders" catalog="test" batch-size="2">
		<id name="id" column="id" type="int">
			<generator class="native"></generator>
		</id>
		<property name="address" column="address" type="java.lang.String"></property>
		<property name="money" column="money" type="double"></property>
		<!-- 在orders表中添加customer外键列,column为外键列名 -->
		<many-to-one name="customer" class="rock.lee.bean.Customer" column="customer_id"   fetch="select" lazy="proxy"></many-to-one>
	</class>
</hibernate-mapping>

 

检索策略的比较
Hibernate part 13:批量检索策略_第1张图片
 

你可能感兴趣的:(Hibernate)