hibernate 批量处理操作


     一: hibernate的批量插入操作:

            hibernate进行批量插入时候,调用jdbc的批量插入效率要远高于hibernate的批量插入;

           1 通过hibernate调用jdbc API完成100000条数据插入:

          

package com.tem.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.SessionFactoryImplementor;

import com.tem.hib.Classes;

public class Test {

	public static void main(String[] args) {
		long ls=System.currentTimeMillis();
		Configuration cfg=new AnnotationConfiguration().configure();		
		SessionFactory sf=cfg.buildSessionFactory();	
		Session session=sf.openSession();
		session.beginTransaction();
		
		try {
			Connection conn=((SessionFactoryImplementor)session.getSessionFactory()).getConnectionProvider().getConnection();
			String sql="insert into classes c values(?,?)";
			PreparedStatement ps=conn.prepareStatement(sql);			
			for(int i=5;i<100005;i++){				
				ps.setInt(1, i);
				ps.setString(2, "C"+i);
				ps.addBatch();	
			}
			ps.executeBatch();		
			conn.commit();			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		session.getTransaction().commit();
		session.close();
		long le=System.currentTimeMillis();
		System.out.println(le-ls);
	}

}


          使用jdbc API执行时间为1000多毫秒;

      

      使用hibernate api执行插入100000条数据:

package com.tem.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.SessionFactoryImplementor;

import com.tem.hib.Classes;

public class Test {

	public static void main(String[] args) {
		long ls=System.currentTimeMillis();
		Configuration cfg=new AnnotationConfiguration().configure();		
		SessionFactory sf=cfg.buildSessionFactory();	
		Session session=sf.openSession();
		session.beginTransaction();
		
		for(int i=5;i<100005;i++){
			Classes c=new Classes();
			c.setCid(i);
			c.setCname("c"+i);
			session.save(c);
			if(i%50==0){
				session.flush();
				session.clear();
			}
		}
		session.getTransaction().commit();
		session.close();
		long le=System.currentTimeMillis();
		System.out.println(le-ls);
	}

}


        hibernate API执行完是5000多毫秒;

        所以批量插入时候,尽量通过hibernate调用jdbcqpi来完成插入操作;



       二:   修改和删除,可以通过HQL语句加条件完成批量操作;


























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值