CHAPTER 13 Optimizing fetching and caching (Free web host) 13.1.2 The

CHAPTER 13 Optimizing fetching and caching 13.1.2 The lazy default fetch plan Hibernate defaults to a lazy fetching strategy for all entities and collections. This means that Hibernate by default loads only the objects you re querying for. Let s explore this with a few examples. If you query for an Item object (let s say you load it by its identifier), exactly this Item and nothing else is loaded into memory: Item item = (Item) session.load(Item.class, new Long(123)); This retrieval by identifier results in a single (or possibly several, if inheritance or secondary tables are mapped) SQL statement that retrieves an Item instance. In the persistence context, in memory, you now have this item object available in persistent state, as shown in figure 13.1. Figure 13.1 An uninitialized placeholder for an Item instance We ve lied to you. What is available in memory after the load() operation isn t a persistent item object. Even the SQL that loads an Item isn t executed. Hibernate created a proxy that looks like the real thing. 13.1.3 Understanding proxies Proxies are placeholders that are generated at runtime. Whenever Hibernate returns an instance of an entity class, it checks whether it can return a proxy instead and avoid a database hit. A proxy is a placeholder that triggers the loading of the real object when it s accessed for the first time: Item item = (Item) session.load(Item.class, new Long(123)); item.getId(); item.getDescription(); // Initialize the proxy The third line in this example triggers the execution of the SQL that retrieves an Item into memory. As long as you access only the database identifier property, no initialization of the proxy is necessary. (Note that this isn t true if you map the identifier property with direct field access; Hibernate then doesn t even know that the getId() method exists. If you call it, the proxy has to be initialized.)
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

Leave a Reply