Overview
No memory waste: When Hibernate loads the Customer object from the database, if it loads all the associated Order objects at the same time, and the program actually only needs to access the Customer object, then these associated Order objects waste a lot of memory.
Higher query efficiency: Send as few SQL statements as possible
Category-level search policy
Optional search policies at the class level include instant retrieval and delayed retrieval. The default is delayed retrieval. Instant retrieval: loading the objects specified by the search method immediately. Delayed retrieval: delays loading the objects specified by the search method. When you use a specific attribute, you can use Set the lazy attribute of the element. If the program loads an object to access its properties, it can immediately retrieve it.
If the program loads a persistent object for the purpose of obtaining its reference only, you can use delayed retrieval. Note that an error occurred while loading resources!
Regardless The lazy attribute of the element is true or false. The get () method of the Session and the list () method of the Query always use the immediate retrieval policy at the class level.
If The lazy attribute of the element is true or the default value is used. The load () method of the Session does not execute the SELECT statement for querying the data table, but only returns the instance of the proxy class object. This proxy class instance has the following features: dynamically generated by Hibernate using CGLIB during runtime
When Hibernate creates a proxy instance, it only initializes its OID attribute. When the application first accesses the non-OID attribute of the proxy instance, Hibernate initializes the proxy instance.
One-to-many and multiple-to-many retrieval policies
In the ing file, use Element to configure one-to-multiple associations and multiple-to-multiple associations. The lazy and fetch attributes of the elements are lazy, which mainly determines the time when the orders set is initialized. whether it is initialized when the Customer object is loaded or when the program accesses the orders set fetch: When the value is "select" or "subselect, determines the form of the query statement for initializing orders. If the value is "join", it determines Z limit? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vcmRlcnMgvK + 6z7G7s/extensions/ey38LUu/extensions + connectors/cS/LCDM4bjf0dOz2bzsy/extensions + connectors" http://www.2cto.com/uploadfile/Collfiles/20140602/20140602090327206.png "alt = "\">
Latency retrieval and enhanced latency Retrieval
When the set property of delayed retrieval (the lazy property value is true), Hibernate initializes the set property for the first access by the collection proxy instance application in the following cases: iterator (), size (), isEmpty (), contains (), and other methods
Explicit initialization through Hibernate. initialize () Static Method
Enhanced latency search (lazy attribute is extra): similar to lazy = "true. the main difference is that the enhanced latency search policy can further delay the initialization time of the orders set proxy instance of the Customer object: when the program first accesses the iterator () method of the orders attribute, this will cause initialization of the orders set proxy class instance. When the program first accesses the size (), contains (), and isEmpty () Methods of the order attribute, Hibernate will not initialize the orders set class instance, only query the required information through a specific select statement. No Order object is retrieved.
Batch-size attribute of the element The element has a batch-size attribute, which is used to set the number of batch searches for delayed or instant retrieval policies. batch search can reduce the number of SELECT statements and improve the running performance of delayed search or instant search.
Initialize the orders set in batches using the select statement of the query with the substring (the fetch attribute is "subselect ")
Element fetch attribute: When the value is "select" or "subselect", it determines the form of the query statement for initializing orders. If the value is "join ", determines the time when the orders set is initialized. the default value is select.
When the fetch attribute is "subselect", it is assumed that n orders set proxy instances are not initialized in the Session cache. Hibernate can use the select statement to query the strings to initialize n orders set proxy instances in batches.
The batch-size attribute is ignored.
The select statement in the subquery is the SELECT statement used to query the OID of the MERs table.
Urgent left Outer join search (the fetch attribute value is set to "join ")
Element fetch attribute: When the value is "select" or "subselect", it determines the form of the query statement for initializing orders. If the value is "join ", determines the time when the orders set is initialized. the default value is select. When the fetch attribute is "join": when the Customer object is retrieved, an urgent left Outer join is used (the objects associated with the specified object are loaded and retrieved through the left Outer join) policy to retrieve all associated Order objects
The list () method of the Query that will be ignored by the lazy attribute ignores the urgent left Outer Join search policy configured in the ing file, and uses the delayed loading policy.
Multiple-to-one and one-to-one Retrieval Strategies
And Same, The element also has a lazy attribute and a fetch attribute.
If the fetch attribute is set to join, the lazy attribute is ignored. The advantage of the pressing left Outer join search policy is that it uses fewer SELECT statements than the instant search policy. the listquery method requires enhanced persistence class bytecode for delayed retrieval without proxy, and ignores the urgent left Outer Join search policy configured in the ing file, if the latency search policy is used at the association level, you can set the size of the batch search to improve the running performance of the delayed search or instant search. hibernate allows you to overwrite the retrieval policy set in the ing file in the application.
Search policy summary
Optional search policies and default search policies at the class level and association level
Operating Mechanisms of the three retrieval policies
Attributes used to set the search policy in the ing File
Compare the three Retrieval Strategies of Hibernate
Code details: Customer. java
package com.atguigu.hibernate.strategy;import java.util.HashSet;import java.util.Set;public class Customer {private Integer customerId;private String customerName;private Set
orders = new HashSet<>();public Integer getCustomerId() {return customerId;}public void setCustomerId(Integer customerId) {this.customerId = customerId;}public String getCustomerName() {return customerName;}public void setCustomerName(String customerName) {this.customerName = customerName;}public Set
getOrders() {return orders;}public void setOrders(Set
orders) {this.orders = orders;}}
Order. java
package com.atguigu.hibernate.strategy;public class Order {private Integer orderId;private String orderName;private Customer customer;public Integer getOrderId() {return orderId;}public void setOrderId(Integer orderId) {this.orderId = orderId;}public String getOrderName() {return orderName;}public void setOrderName(String orderName) {this.orderName = orderName;}public Customer getCustomer() {return customer;}public void setCustomer(Customer customer) {this.customer = customer;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Order other = (Order) obj;if (orderId == null) {if (other.orderId != null)return false;} else if (!orderId.equals(other.orderId))return false;return true;}}
Customer. hbm. xml
Order. hbm. xml
Package com. atguigu. hibernate. strategy; import java. util. list; import org. hibernate. hibernate; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; import org. hibernate. service. serviceRegistry; import org. hibernate. service. serviceRegistryBuilder; import org. junit. after; import org. junit. before; import org. junit. test; public class HibernateTest {private SessionFactory sessionFactory; private Session session; private Transaction transaction; @ Beforepublic void init () {Configuration configuration Configuration = new Configuration (). configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); sessionFactory = configuration. buildSessionFactory (serviceRegistry); session = sessionFactory. openSession (); transaction = session. beginTransaction () ;}@ Afterpublic void destroy () {transaction. commit (); session. close (); sessionFactory. close () ;}@ Testpublic void testMany2OneStrategy () {// Order order = (Order) session. get (Order. class, 1); // System. out. println (order. getCustomer (). getCustomerName (); List
Orders = session. createQuery ("FROM Order o"). list (); for (Order order: orders) {if (order. getCustomer ()! = Null) {System. out. println (order. getCustomer (). getCustomerName ();} // 1. the value of lazy is proxy and false, respectively, indicating that the corresponding attribute uses delayed search and instant search. // 2. the value of fetch is join, indicating that the lazy attribute is initialized at one end of n join 1 by pressing the left Outer join. // The lazy attribute is ignored. // 3. batch-size, which must be set in the class element at the end of 1 ://
// Purpose: Initialize the number of proxy objects in 1 at a time .} @ Testpublic void testSetFetch2 () {Customer customer Customer = (Customer) session. get (Customer. class, 1); System. out. println (customer. getOrders (). size () ;}@ Testpublic void testSetFetch () {List
MERs = session. createQuery ("FROM Customer "). list (); System. out. println (MERS MERs. size (); for (Customer customer: MERs mers) {if (customer. getOrders ()! = Null) System. out. println (customer. getOrders (). size ();} // The fetch attribute of the set: determines how the orders set is initialized. // 1. the default value is select. initialize the set element in the normal way. // 2. the value can be subselect. all set sets are initialized by subqueries. subquery // The in condition that is used as the where clause. The subquery queries the ID of each end of 1. in this case, lazy is valid. // but the batch-size is invalid. // 3. if the value is join. then // 3.1 When loading objects at one end of 1, use the urgent left outer link (use the left outer link for query and initialize the set attributes) to retrieve the set attributes of n. // 3.2 ignore the lazy attribute. // 3.3 ignore the value of fetch = join in HQL query} @ Testpublic void testSetBatchSize () {List
MERs = session. createQuery ("FROM Customer "). list (); System. out. println (MERS MERs. size (); for (Customer customer: MERs mers) {if (customer. getOrders ()! = Null) System. out. println (customer. getOrders (). size ();} // set the batch-size attribute of the element: set the number of set sets to be initialized at a time .} @ Testpublic void testOne2ManyLevelStrategy () {Customer customer = (Customer) session. get (Customer. class, 1); System. out. println (customer. getCustomerName (); System. out. println (customer. getOrders (). size (); Order order = new Order (); order. setOrderId (1); System. out. println (customer. getOrders (). contains (or Der); Hibernate. initialize (customer. getOrders (); // --------------- set's lazy attribute ------------------ // 1. by default, the set attributes of 1-n or n-n are lazy loaded. // 2. you can modify the default search policy by setting the set lazy attribute. the default value is true // It is not recommended to set it to false. // 3. lazy can also be set to extra. enhanced latency retrieval. this value will delay the set initialization time as much as possible !} @ Testpublic void testClassLevelStrategy () {Customer customer = (Customer) session. load (Customer. class, 1); System. out. println (customer. getClass (); System. out. println (customer. getCustomerId (); System. out. println (customer. getCustomerName ());}}