CHAPTER 13 Optimizing fetching and caching By default, (Free web hosting services)
CHAPTER 13 Optimizing fetching and caching By default, Hibernate fetches associated objects and collections lazily whenever you access them (we assume that you map all to-one associations as FetchType. LAZY if you use Java Persistence). Look at the following trivial code example: Item item = (Item) session.get(Item.class, new Long(123)); You didn t configure any association or collection to be nonlazy, and that proxies can be generated for all associations. Hence, this operation results in the following SQL SELECT: select item.* from ITEM item where item.ITEM_ID = ? (Note that the real SQL Hibernate produces contains automatically generated aliases; we ve removed them for readability reasons in all the following examples.) You can see that the SELECT queries only the ITEM table and retrieves a particular row. All entity associations and collections aren t retrieved. If you access any proxied association or uninitialized collection, a second SELECT is executed to retrieve the data on demand. Your first optimization step is to reduce the number of additional on-demand SELECTs you necessarily see with the default lazy behavior for example, by prefetching data. 13.2.1 Prefetching data in batches If every entity association and collection is fetched only on demand, many additional SQL SELECT statements may be necessary to complete a particular procedure. For example, consider the following query that retrieves all Item objects and accesses the data of each items seller: List allItems = session.createQuery(”from Item”).list(); processSeller( (Item)allItems.get(0) ); processSeller( (Item)allItems.get(1) ); processSeller( (Item)allItems.get(2) ); Naturally, you use a loop here and iterate through the results, but the problem this code exposes is the same. You see one SQL SELECT to retrieve all the Item objects, and an additional SELECT for every seller of an Item as soon as you process it. All associated User objects are proxies. This is one of the worst-case scenarios we ll describe later in more detail: the n+1 selects problem. This is what the SQL looks like: select items… select u.* from USERS u where u.USER_ID = ? select u.* from USERS u where u.USER_ID = ?
We recommend high quality webhost to host and run your jsp application: christian web host services.