检索数据时的 2 个问题:
- 不浪费内存:当 Hibernate 从数据库中加载 Customer 对象时, 如果同时加载所有关联的 Order 对象, 而程序实际上仅仅需要访问 Customer 对象, 那么这些关联的 Order 对象就白白浪费了许多内存。
- 更高的查询效率:发送尽可能少的 SQL 语句。
其实检索策略就是围绕内存和效率这两个核心问题来展开的。
【1】类级别的检索策略
类级别可选的检索策略包括立即检索和延迟检索, 默认为延迟检索。
- 立即检索: 立即加载检索方法指定的对象
- 延迟检索: 延迟加载检索方法指定的对象。在使用具体的属性时,再进行加载
类级别的检索策略可以通过 <class>
元素的 lazy 属性进行设置(注意出现懒加载异常)。
如果程序加载一个对象的目的是为了访问它的属性, 可以采取立即检索。
如果程序加载一个持久化对象的目的是仅仅为了获得它的引用, 可以采用延迟检索。
不过需要注意的是无论<class>
元素的 lazy 属性是 true 还是 false, Session 的 get() 方法及 Query 的 list() 方法在类级别总是使用立即检索策略。
若 <class>
元素的 lazy 属性为 true 或取默认值, Session 的 load() 方法不会执行查询数据表的 SELECT 语句, 仅返回代理类对象的实例, 该代理类实例有如下特征:
- 由 Hibernate 在运行时采用 CGLIB 工具动态生成
- Hibernate 创建代理类实例时, 仅初始化其 OID 属性
- 在应用程序第一次访问代理类实例的非 OID 属性时, Hibernate 会初始化代理类实例。
测试代码如下:
@Test public void testClassLevelStrategy(){ Customer customer = (Customer) session.load(Customer.class, 1); System.out.println(customer.getClass()); }
默认情况下,使用懒加载方式,将会得到Customer的代理对象,如下所示:
class com.jane.strategy.Customer_$$_jvstf42_1
修改Customer.hbm.xml在class节点将属性lazy设置为false:
<class name="Customer" table="CUSTOMERS" lazy="false" > //... </class>
再次测试结果如下:
Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_0_ from CUSTOMERS customer0_ where customer0_.CUSTOMER_ID=? class com.jane.strategy.Customer
再次将lazy设置为true,测试代码如下:
@Test public void testClassLevelStrategy(){ Customer customer = (Customer) session.load(Customer.class, 4); System.out.println(customer.getClass()); System.out.println(customer.getCustomerId()); System.out.println(customer.getCustomerName()); }
测试结果如下:
class com.jane.strategy.Customer_$$_jvstf42_1 4 Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_0_ from CUSTOMERS customer0_ where customer0_.CUSTOMER_ID=? AA
可以看到 load懒加载时,代理对象实例拥有属性值OID为4,访问其他属性时才发送select查询。
【2】一对多和多对多的检索策略
在映射文件中, 用 <set>
元素来配置一对多关联及多对多关联关系。
<set>
元素有 lazy 和 fetch及 batch-size 属性:
- lazy: 主要决定 orders 集合被初始化的时机。 即到底是在加载 Customer 对象时就被初始化, 还是在程序访问 orders 集合时被初始化(默认值lazy=true)。
- fetch: 取值为 “select” 或 “subselect” 时, 决定初始化 orders 的查询语句的形式; 若取值为”join”, 则决定 orders 集合被初始化的时机。若把 fetch 设置为 “join”, lazy 属性将被忽略。
- batch-size 属性:用来为延迟检索策略或立即检索策略设定批量检索的数量。批量检索能减少 SELECT 语句的数目, 提高延迟检索或立即检索的运行性能。
① 测试lazy
默认set节点的lazy属性为true,则在程序访问orders集合时发送select查询orders。
测试代码如下:
@Test public void testOne2ManyLevelStrategy(){ Customer customer = (Customer) session.get(Customer.class, 4); System.out.println(customer.getCustomerName()); System.out.println(customer.getOrders().size()); }
测试结果如下:
Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_0_ from CUSTOMERS customer0_ where customer0_.CUSTOMER_ID=? AA Hibernate: select orders0_.CUSTOMER_ID as CUSTOMER3_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_1_, orders0_.ORDER_NAME as ORDER_NA2_1_1_, orders0_.CUSTOMER_ID as CUSTOMER3_1_1_ from ORDERS orders0_ where orders0_.CUSTOMER_ID=? order by orders0_.ORDER_NAME desc 2
若将set节点的lazy属性设置为false,则在查询Customer时立即查询关联的Order。
如下所示:
Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_0_ from CUSTOMERS customer0_ where customer0_.CUSTOMER_ID=? Hibernate: select orders0_.CUSTOMER_ID as CUSTOMER3_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_1_, orders0_.ORDER_NAME as ORDER_NA2_1_1_, orders0_.CUSTOMER_ID as CUSTOMER3_1_1_ from ORDERS orders0_ where orders0_.CUSTOMER_ID=? order by orders0_.ORDER_NAME desc AA 2
② 延迟检索和增强延迟检索
在延迟检索(lazy 属性值为 true) 集合属性时, Hibernate 在以下情况下初始化集合代理类实例 :
- 应用程序第一次访问集合属性: iterator(), size(), isEmpty(), contains() 等方法;
- 通过 Hibernate.initialize() 静态方法显式初始化;
增强延迟检索(lazy 属性为 extra) 与 lazy=“true” 类似,主要区别是增强延迟检索策略能进一步延迟 Customer 对象的 orders 集合代理实例的初始化时机:
- 当程序第一次访问 orders 属性的 iterator() 方法时, 会导致 orders 集合代理类实例的初始化;
- 当程序第一次访问 order 属性的 size(), contains() 和 isEmpty() 方法时, Hibernate 不会初始化 orders 集合类的实例, 仅通过特定的 select 语句查询必要的信息, 不会检索所有的 Order 对象。
测试代码如下(lazy=“extra”):
@Test public void testOne2ManyLevelStrategy(){ Customer customer = (Customer) session.get(Customer.class, 4); System.out.println(customer.getCustomerName()); System.out.println(customer.getOrders().size()); Hibernate.initialize(customer.getOrders()); }
测试结果如下:
Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_0_ from CUSTOMERS customer0_ where customer0_.CUSTOMER_ID=? AA Hibernate: select count(ORDER_ID) from ORDERS where CUSTOMER_ID =? 2 Hibernate: select orders0_.CUSTOMER_ID as CUSTOMER3_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_1_, orders0_.ORDER_NAME as ORDER_NA2_1_1_, orders0_.CUSTOMER_ID as CUSTOMER3_1_1_ from ORDERS orders0_ where orders0_.CUSTOMER_ID=? order by orders0_.ORDER_NAME desc
③ 测试batch-size
不设置set节点的batch-size属性时,测试代码如下:
@Test public void testSetBatchSize(){ List<Customer> customers = session.createQuery("FROM Customer").list(); System.out.println(customers.size()); for(Customer customer: customers){ if(customer.getOrders() != null) System.out.println(customer.getOrders().size()); } }
测试结果如下:
Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_ from CUSTOMERS customer0_ 2 Hibernate: select orders0_.CUSTOMER_ID as CUSTOMER3_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_1_, orders0_.ORDER_NAME as ORDER_NA2_1_1_, orders0_.CUSTOMER_ID as CUSTOMER3_1_1_ from ORDERS orders0_ where orders0_.CUSTOMER_ID=? order by orders0_.ORDER_NAME desc 3 Hibernate: select orders0_.CUSTOMER_ID as CUSTOMER3_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_0_, orders0_.ORDER_ID as ORDER_ID1_1_1_, orders0_.ORDER_NAME as ORDER_NA2_1_1_, orders0_.CUSTOMER_ID as CUSTOMER3_1_1_ from ORDERS orders0_ where orders0_.CUSTOMER_ID=? order by orders0_.ORDER_NAME desc 3
即, 有多少customer,就需要发送多少条SQL来额外查询关联的order。
为Customer.hbm.xml的set节点设置batch-size属性如下:
<set name="orders" table="ORDERS" inverse="true" order-by="ORDER_NAME DESC" batch-size="2"> <key column="CUSTOMER_ID"></key> <one-to-many class="Order"/> </set>
测试结果如下:
Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_ from CUSTOMERS customer0_ 2 Hibernate: select orders0_.CUSTOMER_ID as CUSTOMER3_1_1_, orders0_.ORDER_ID as ORDER_ID1_1_1_, orders0_.ORDER_ID as ORDER_ID1_1_0_, orders0_.ORDER_NAME as ORDER_NA2_1_0_, orders0_.CUSTOMER_ID as CUSTOMER3_1_0_ from ORDERS orders0_ where orders0_.CUSTOMER_ID in ( ?, ? ) order by orders0_.ORDER_NAME desc 3 3
此时只额外发送了一条(batch-size>=cutomers.size)SQL语句来初始化关联的order。
④ set节点的fetch属性
fetch默认值为select,即以select语句的形式查询关联实体。若取值为”join”, 则决定 orders 集合被初始化的时机。若把 fetch 设置为 “join”, lazy 属性将被忽略。
当 fetch 属性为 “subselect” 时:
- 假定 Session 缓存中有 n 个 orders 集合代理类实例没有被初始化, Hibernate 能够通过带子查询的 select 语句, 来批量初始化 n 个 orders 集合代理类实例;
- batch-size 属性将被忽略;
- 子查询中的 select 语句为查询 CUSTOMERS 表 OID 的 SELECT 语句。
将Customer.hbm.xml的set节点中fetch属性设置为subselect,测试代码如下:
<set name="orders" table="ORDERS" inverse="true" order-by="ORDER_NAME DESC" batch-size="2" fetch="subselect"> <key column="CUSTOMER_ID"></key> <one-to-many class="Order"/> </set>
@Test public void testSetBatchSize(){ List<Customer> customers = session.createQuery("FROM Customer").list(); System.out.println(customers.size()); for(Customer customer: customers){ if(customer.getOrders() != null) System.out.println(customer.getOrders().size()); } }
测试结果如下:
Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_ from CUSTOMERS customer0_ 2 Hibernate: select orders0_.CUSTOMER_ID as CUSTOMER3_1_1_, orders0_.ORDER_ID as ORDER_ID1_1_1_, orders0_.ORDER_ID as ORDER_ID1_1_0_, orders0_.ORDER_NAME as ORDER_NA2_1_0_, orders0_.CUSTOMER_ID as CUSTOMER3_1_0_ from ORDERS orders0_ where orders0_.CUSTOMER_ID in ( select customer0_.CUSTOMER_ID from CUSTOMERS customer0_ ) //这里用到了子查询 order by orders0_.ORDER_NAME desc 3 3
通过子查询的方式来初始化所有的 set 集合。子查询作为 where 子句的 in 的条件出现, 子查询查询所有 1 的一端的 ID, 此时 lazy 有效但batch-size失效。
迫切左外连接检索–将fetch设置为join
当 fetch 属性为 “join” 时:
- 检索 Customer 对象时, 会采用迫切左外连接(通过左外连接加载与检索指定的对象关联的对象)策略来检索所有关联的 Order 对象;
- lazy 属性将被忽略;
- Query 的list() 方法会忽略映射文件中配置的迫切左外连接检索策略, 而依旧采用延迟加载策略。
set节点lazy和fetch属性组合情况
【3】多对一和一对一关联的检索策略
和 <set>
一样,<many-to-one>
元素也有一个 lazy 属性和 fetch 属性。
注意,many-to-one节点lazy属性和fetch属性取值与set节点的不同。
Note:
- 若 fetch 属性设为 join, 那么 lazy 属性被忽略;
- 迫切左外连接检索策略的优点在于比立即检索策略使用的 SELECT 语句更少.;
- 无代理延迟检索需要增强持久化类的字节码才能实现;
- Query 的 list 方法会忽略映射文件配置的迫切左外连接检索策略, 而采用延迟检索策略;
- 如果在关联级别使用了延迟加载或立即加载检索策略, 可以设定批量检索的大小, 以帮助提高延迟检索或立即检索的运行性能.;
- Hibernate 允许在应用程序中覆盖映射文件中设定的检索策略。
① 测试一-lazy=false,fetch=join
配置文件Order.hbm.xml如下:
<many-to-one name="customer" class="Customer" column="CUSTOMER_ID" lazy="false" fetch="join"> </many-to-one>
测试代码如下:
@Test public void testMany2OneStrategy(){ Order order = (Order) session.get(Order.class, 7); System.out.println(order.getCustomer().getCustomerName()); }
测试结果如下:
Hibernate: select order0_.ORDER_ID as ORDER_ID1_1_0_, order0_.ORDER_NAME as ORDER_NA2_1_0_, order0_.CUSTOMER_ID as CUSTOMER3_1_0_, customer1_.CUSTOMER_ID as CUSTOMER1_0_1_, customer1_.CUSTOMER_NAME as CUSTOMER2_0_1_ from ORDERS order0_ left outer join CUSTOMERS customer1_ on order0_.CUSTOMER_ID=customer1_.CUSTOMER_ID where order0_.ORDER_ID=? AA
无论是fetch属性设置为join或者HQL显示使用left join fetch关键字,都会对应标准SQLleft outer join
。
② 测试class节点的batch-size属性
遍历orders关联的customers,此时需要在Customer.hbm.xml中的class节点设置batch-size属性:
<class name="Customer" table="CUSTOMERS" lazy="true" batch-size="5">
作用为 一次初始化 1 的这一端代理对象的个数。
测试代码如下:
@Test public void testMany2OneStrategy(){ List<Order> orders = session.createQuery("FROM Order o").list(); for(Order order: orders){ if(order.getCustomer() != null){ System.out.println(order.getCustomer().getCustomerName()); } } }
测试结果如下:
Hibernate: select order0_.ORDER_ID as ORDER_ID1_1_, order0_.ORDER_NAME as ORDER_NA2_1_, order0_.CUSTOMER_ID as CUSTOMER3_1_ from ORDERS order0_ Hibernate: select customer0_.CUSTOMER_ID as CUSTOMER1_0_0_, customer0_.CUSTOMER_NAME as CUSTOMER2_0_0_ from CUSTOMERS customer0_ where customer0_.CUSTOMER_ID in ( ?, ? ) AA AA BB BB AA BB
【4】检索策略小结
① 类级别和关联级别可选的检索策略及默认的检索策略
② 3种检索策略的运行机制
③ 映射文件中用于检索策略的几个属性
batch-size:设定批量检索的数量可选值为一个正整数,合理的取值范围为3-10。仅适用于关联级别的立即检索和延迟检索。在class节点和set节点中均有次属性。
④ 三种检索策略优缺点