Batch insert in Hibernate

This example program shows how to insert multiple rows using the batch processing in hibernate. when there are thousand of rows to be persisted, everytime iterating and inserting will cause the memory problem. Hibernate stores all the persisted objects in the memory. To avoid this problem use batch processing in the hibernate.

also read:

To use the batch processing feature, first set hibernate.jdbc.batch_size as 50. This will tell the hibernate container that every 50 rows to be inserted as batch. Also there is a slight change in the code.

for (int i =0;i<100;i++)
        {
            EmployeeInfo employeeInfo = new EmployeeInfo();
            employeeInfo.setSno(1);;
            employeeInfo.setName("Value : "+String.valueOf(i));
            session.save(employeeInfo);
            if (i%50 == 0)
            {
                session.flush();
                session.clear();
            }
        }

the above code is used for inserting 50 rows. Do remember to call session.flush() every time. That will make the data to be persisted.

JavaBeatHibernateExample.java

package javabeat.net.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 * source : www.javabeat.net
 */
public class JavaBeatHibernateExample {
    public static void main(String args[]){
        Configuration configuration = new Configuration();
        configuration.addClass(javabeat.net.hibernate.EmployeeInfo.class);
        configuration.setProperty("hibernate.dialect",
                "org.hibernate.dialect.DerbyDialect");
        configuration.setProperty("hibernate.connection.url",
                "jdbc:derby://localhost:1527/SampleDB");
        configuration.setProperty("hibernate.connection.username", "root");
        configuration.setProperty("hibernate.connection.driver_class",
                "org.apache.derby.jdbc.ClientDriver");
        configuration.setProperty("hibernate.connection.password", "root");
        configuration.setProperty("hibernate.transaction.factory_class",
                "org.hibernate.transaction.JDBCTransactionFactory");
        configuration.setProperty("hibernate.current_session_context_class",
                "thread");
        configuration.setProperty("hibernate.show_sql", "true");
        configuration.setProperty("hibernate.jdbc.batch_size", "50");
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        for (int i =0;i<100;i++)
        {
            EmployeeInfo employeeInfo = new EmployeeInfo();
            employeeInfo.setSno(1);;
            employeeInfo.setName("Value : "+String.valueOf(i));
            session.save(employeeInfo);
            if (i%50 == 0)
            {
                session.flush();
                session.clear();
            }
        }
        transaction.commit();
        session.close();
    }
}

EmployeeInfo.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
    <class name="javabeat.net.hibernate.EmployeeInfo" table="Employee_Info">
        <id name="sno" column="sno" type="java.lang.Integer">
           <generator class="increment"/>
        </id>
        <property name="name" column="name" type="java.lang.String"/>
    </class>
</hibernate-mapping>

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Hello!

    I tried this method and it works only for the product_id in the Product table.

    The other columns have setters, that have a Class parameter, for example setProviderId(Provider provider) and my provider_id is int.

    Should I cast it or how should I proceed?

  2. Hello!

    I tried this method and it works only for the product_id in the Product table.

    The other columns in the Product table have setters, that have a Class parameter, for example setProviderId(Provider provider) and my provider_id is int.

    Should I cast it or how should I proceed?

  3. help me please !!, thanks you very much !!
    =>>my code :
    public static void main(String[] args) { SessionFactory sessFact=HibernateUtil.getSessionFactory(); org.hibernate.Session sess=sessFact.openSession(); sess.beginTransaction(); SinhVien sv=new SinhVien(); sv.setHoTen(“Ngo Thanh Long”); sv.setNgaySinh(“12-03-1985″); sv.setDiaChi(“345 Vo thi Sau ,P.12,Q.3″); sv.setMaLop(“CDTH12A”); sess.save(sv); sess.getTransaction().commit(); sess.close(); System.out.println(“Successfull !!!”); }
    =>>But it dont run in following function :
    public static void add_SV(String hoten,String ngaysinh,String diachi,String malop){ SessionFactory sessFact=HibernateUtil.getSessionFactory(); org.hibernate.Session sess=sessFact.openSession(); sess.beginTransaction(); SinhVien sv=new SinhVien(); sv.setHoTen(hoten); sv.setNgaySinh(ngaysinh); sv.setDiaChi(diachi); sv.setMaLop(malop); sess.save(sv); sess.getTransaction().commit(); sess.close();
    }
    =>>error Message :

    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)at javax.swing.DefaultButtonModel.setPressed(Unknown Source)

Trackbacks

  1. […] El  API de JPA no proporciona las opciones para hacer óptimo el proceso de guardar masivamente registros, en su defecto el  ORM de Hibernate usa el API JDBC batch a través de la propiedad hibernate.jdbc.batch_size, para obtener más información de esta opción  consulte el siguiente link : http://www.javabeat.net/2008/07/batch-insert-in-hibernate/ […]

Speak Your Mind

*