hibernate 批量插入数据

在Hibernate的配置文件 hibernate.cfg.xml中设置批量尺寸属性"hibernate.jdbc.batch_size",且推荐关闭Hibernate的二级缓存以提高效率.如:
<hibernate-configuration>
    <session-factory>
     .......
        <property name="hibernate.jdbc.batch_size>这里填你想要的大小值,如50</property>
        <property name="hiberante.cache.use_second_level_cache">false</property>
     .......
    </session-factory>
</hibernate-configuration> 

Session session = getHibernateTemplate().getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		try{
			for(int i=0;i<list.size();i++){
				session.save((YPrice)list.get(i));
				
				if(i%1000==0){
					session.flush();
					session.clear();
				}
			}
			
			tx.commit();
		}catch(HibernateException   e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}


JDBC
Connection con = session.connection();
PreparedStatement stmt = con.prepareStatement("insert into table_name values(?)");
for (int i=0; i<1000; i++)
{
      stmt.setString(1, "value"+i);
      stmt.addBatch();//将插入的任务添加到批处理中.
}
stmt.executeBatch();//执行批量任务 
ts.commit();
session.close();

猜你喜欢

转载自henghengdh.iteye.com/blog/1740858