Hibernate Batch processing
Normally basic approach for inserting 100,000 rows in the database using Hibernate may fails in OutOfMemoryException.
If you are undertaking batch processing you will need to enable the use of JDBC batching. This is absolutely essential if you want to achieve optimal performance. Set the JDBC batch size to a reasonable number.
<property name="hibernate.jdbc.batch_size">50</property>
Inserting bulk data using hibernate batch process
When making new objects persistent flush() and then clear() the session regularly in order to control the size of the first-level cache.
public void addEmployees() { Session s = getSession(); Transaction tx = null; try { tx = s.beginTransaction(); for (int i = 10; i < 200; i++) { String fname = "candidjava " + i; Integer age = i + 10; String city = "City " + i; Integer salary = i + 1000; String gender; if (i % 2 == 0) { gender = "Male"; } else { gender = "Female"; } Employee employee = new Employee(fname, age, salary, city, gender); s.save(employee); if (i % 20 == 0) { s.flush(); s.clear(); } } tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); e.printStackTrace(); } finally { s.close(); } }
Updating bulk record using hibernate batch processing.
For retrieving and updating data, the same ideas apply. In addition, you need to use scroll() to take advantage of server-side cursors for queries that return many rows of data.
public void updateEmployees() { Session s = getSession(); Transaction tx = null; try { tx = s.beginTransaction(); ScrollableResults empCursor = s.createQuery("FROM Employee") .scroll(); int count = 0; while (empCursor.next()) { Employee employ = (Employee) empCursor.get(0); employ.setName("Naty"); s.update(employ); if (++count % 20 == 0) { s.flush(); s.clear(); } } tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); e.printStackTrace(); } finally { s.close(); } }
Download