Caching in practice 13.4.5 Controlling the second-level cache (Starting a web site)

Caching in practice 13.4.5 Controlling the second-level cache Hibernate has some useful methods that can help you test and tune your cache. Consider the global configuration switch for the second-level cache, hibernate. cache.use_second_level_cache. By default, any element in your mapping files (or in hibernate.cfg.xml, or an annotation) triggers the second-level cache and loads the cache provider at startup. If you want to disable the second- level cache globally without removing the cache mapping elements or annotations, set this configuration property to false. Just as the Session and EntityManager provide methods for controlling the persistence context first-level cache programmatically, so does the SessionFactory for the second-level cache. In a JPA application, you have to get access to the underlying internal SessionFactory, as described in chapter 2, section 2.2.4, Switching to Hibernate interfaces. You can call evict() to remove an element from the second-level cache by specifying the class and the object identifier value: SessionFactory.evict( Category.class, new Long(123) ); You may also evict all elements of a certain class or only evict a particular collection role by specifying a region name: SessionFactory.evict(”auction.model.Category”); You ll rarely need these control mechanisms. Also note that eviction of the sec ond-level cache is nontransactional, that is, the cache region isn t locked during eviction. Hibernate also offers CacheMode options that can be activated for a particular Session. Imagine that you want to insert many objects into the database in one Session. You need to do this in batches, to avoid memory exhaustion every object is added to the first-level cache. However, it s also added to the second-level cache, if enabled for the entity class. A CacheMode controls the interaction of Hibernate with the second-level cache: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.setCacheMode(CacheMode.IGNORE); for ( int i=0; i<100000; i++ ) { Item item = new Item(...); session.save(item); if ( i % 100 == 0 ) { session.flush(); session.clear();
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Leave a Reply