The largest Interview Solution Library on the web


Hibernate Tutorials/
« Previous | 1 | 2 | 3 | Next »
Consider a situation when you need to upload a large number of records into your database using Hibernate. Following is the code snippet to achieve this using Hibernate:

Session session =SessionFactory.openSession();
Transaction tx =session.beginTransaction();
for(int i=0; i<100000; i++){
Employee employee =newEmployee(.....);
session.save(employee);
}
tx.commit();
session.close();

Because by default, Hibernate will cache all the persisted objects in the session-level cache and ultimately your application would fall over with anOutOfMemoryException somewhere around the 50,000th row. You can resolve this problem if you are using batch processing with Hibernate.
To use the batch processing feature, first set hibernate.jdbc.batch_size as batch size to a number either at 20 or 50 depending on object size. This will tell the hibernate container that every X rows to be inserted as batch. To implement this in your code we would need to do little modification as follows:

Session session =SessionFactory.openSession();
Transaction tx =session.beginTransaction();
for(int i=0; i<100000; i++){
Employee employee =newEmployee(.....);
session.save(employee);
if( i %50==0){// Same as the JDBC batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();

Above code will work fine for the INSERT operation, but if you are willing to make UPDATE operation then you can achieve using the following code:

Session session =sessionFactory.openSession();
Transaction tx =session.beginTransaction();

ScrollableResults employeeCursor =session.createQuery("FROM EMPLOYEE")
.scroll();
int count =0;

while( employeeCursor.next()){
Employee employee =(Employee)employeeCursor.get(0);
employee.updateEmployee();
seession.update(employee);
if(++count %50==0){
session.flush();
session.clear();
}
}
tx.commit();
session.close();
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com