Home  >  Hibernate

Example of @BatchSize in Hibernate Annotation

By Arvind Rai, January 31, 2013
In hibernate insert or update can be done in batch. What is the need of batch insert or update? By default all the data is inserted in database at the time of transaction commit. Suppose if we have to insert lacks of data in one go then we will go OutOfMemory error. This is because lacks of data will be in memory and will be inserted when transaction is committed. In case of batch insert or update insert or update is done when we do session flush and session clear. We need to set batch size on the entity to enable batch insert or update.
Country.java
package com.concretepage.persistence;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.BatchSize;

@Entity
@BatchSize(size=2)
public class Country implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	private int id;
	private String name;
	public Country(int id,String name){
		this.id=id;
		this.name=name;
	}
	public Country(){
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}
 
HibernateUtil.java
package com.concretepage.util;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.concretepage.persistence.Country;

public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
	    static {
	        try {
	            concreteSessionFactory = new AnnotationConfiguration()
	                    .configure().buildSessionFactory();
	        } catch (Throwable ex) {
	            throw new ExceptionInInitializerError(ex);
	        }
	    }
	    public static Session getSession()
	            throws HibernateException {
	        return concreteSessionFactory.openSession();
	    }
	    
	    public static void main(String... args){
	    	Session session=getSession();
	    	session.beginTransaction();
	    	for(int i=1;i<=4;i++){
	    		Country c = new Country(i,"A"+i);
		    	session.save(c);	
		    	if(i%2==0){
		    		session.flush();
		    		session.clear();
		    	}
	    	}
	    	session.getTransaction().commit();
	    	Query q=session.createQuery("from Country");
	    	List list= q.list();
	        for(Country ct:list){
	        	System.out.println(ct.getName());
	        }
	        
	        session.close();
	    }
	}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us