Trước tiên, bạn phải bắt đầu một đơn vị làm việc. Bắt đầu từ một đơn vị làm việc Khi bắt đầu của một đơn vị làm việc, một ứng dụng có được một thể hiện của phiên từ SessionFactory của ứng dụng:Tại thời điểm này, một bối cảnh mới kiên trì cũng là khởi tạo cho bạn, và nó sẽ quản lý tất cả các đối tượng bạn làm việc trong đó phiên. Các ứng dụng có thể có | 576 CHAPTER 13 Optimizing fetching and caching right thing. As an example imagine a batch size of 20 and a total number of 119 uninitialized proxies that have to be loaded in batches. At startup time Hibernate reads the mapping metadata and creates 11 batch loaders internally. Each loader knows how many proxies it can initialize 20 10 9 8 7 6 5 4 3 2 1. The goal is to minimize the memory consumption for loader creation and to create enough loaders that every possible batch fetch can be produced. Another goal is to minimize the number of SQL selects obviously. To initialize 119 proxies Hibernate executes seven batches you probably expected six because 6 x 20 119 . The batch loaders that are applied are five times 20 one time 10 and one time 9 automatically selected by Hibernate. Batch fetching is also available for collections class name Item table ITEM . set name bids inverse true batch-size 10 key column ITEM_ID one-to-many class Bid set class If you now force the initialization of one bids collection up to 10 more collections of the same type if they re uninitialized in the current persistence context are loaded right away select items. select b. from BID b where in In this case you again have three Item objects in persistent state and touching one of the unloaded bids collections. Now all three Item objects have their bids loaded in a single SELECT. Batch-size settings for entity proxies and collections are also available with annotations but only as Hibernate extensions @Entity @Table name USERS @ size 10 public class User . @Entity public class Item @OneToMany Selecting a fetch strategy 577 @ size 10 private Set Bid bids new HashSet Bid Prefetching proxies and collections with a batch strategy is really a blind guess. It s a smart optimization that can significantly reduce the number of SQL statements that are otherwise necessary to initialize all the objects you re working with. .