CHAPTER 12 Modifying objects efficiently (Web design portfolio) A flush of

CHAPTER 12 Modifying objects efficiently A flush of the persistence context writes the changes you made to the last 100 Item objects to the database. For best performance, you should set the size of the Hibernate (and JDBC) configuration property hibernate.jdbc.batch_size to the same size as your procedure batch: 100. All UDPATE statements that are executed during flushing are then also batched at the JDBC level. (Note that you should disable the second-level cache for any batch operations; otherwise, each modification of an object during the batch procedure must be propagated to the second-level cache for that persistent class. This is an unnecessary overhead. You ll learn how to control the second-level cache in the next chapter.) The Java Persistence API unfortunately doesn t support cursor-based query results. You have to call org.hibernate.Session and org.hibernate.Query to access this feature. The same technique can be used to create and persist a large number of objects. Inserting many objects in batches If you have to create a few hundred or thousand objects in a unit of work, you may run into memory exhaustion. Every object that is passed to insert() or persist() is added to the persistence context cache. A straightforward solution is to flush and clear the persistence context after a certain number of objects. You effectively batch the inserts: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Item item = new Item(...); session.save(item); if ( i % 100 == 0 ) { session.flush(); session.clear(); } } tx.commit(); session.close(); Here you create and persist 100,000 objects, 100 at a time. Again, remember to set the hibernate.jdbc.batch_size configuration property to an equivalent value and disable the second-level cache for the persistent class. Caveat: Hibernate silently disables JDBC batch inserts if your entity is mapped with an identity identifier generator; many JDBC drivers don t support batching in that case.
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

Leave a Reply