一般如果要插入100万条数据,则会写如下代码:
- package org.xiazdong.test;
- import junit.framework.TestCase;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import org.junit.Test;
- import org.xiazdong.Person;
- public class PersonTest extends TestCase{
- @Test
- public void testAdd(){
- long begin = System.currentTimeMillis();
- Configuration config = new Configuration();
- config.configure();
- SessionFactory factory = config.buildSessionFactory();
- Session session = factory.openSession();
- Transaction tx = session.beginTransaction();
- for ( int i=0; i<1000000; i++ ) { //插入100万条数据
- Person person = new Person("xiazdong-"+i,i+20);
- session.save(person);
- }
- tx.commit();
- session.close();
- long end = System.currentTimeMillis();
- System.out.println((end-begin)/1000.0);
- }
- }
此程序正常来说是会报错:
这是因为Hibernate默认会把没有提交的数据全部缓存,但是缓存是不能存入100万条数据的,因此会报错,我们怎么样能够解决呢?
我们可以通过每100个insert语句时,就强制刷入数据库,实现代码如下:
- package org.xiazdong.test;
- import junit.framework.TestCase;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import org.junit.Test;
- import org.xiazdong.Person;
- public class PersonTest extends TestCase{
- @Test
- public void testAdd(){
- long begin = System.currentTimeMillis();
- Configuration config = new Configuration();
- config.configure();
- SessionFactory factory = config.buildSessionFactory();
- Session session = factory.openSession();
- Transaction tx = session.beginTransaction();
- for ( int i=0; i<1000000; i++ ) { //插入100万条数据
- Person person = new Person("xiazdong-"+i,i+20);
- session.save(person);
- if(i%100==0){ //每一千条刷新并写入数据库
- session.flush();
- session.clear();
- }
- }
- tx.commit();
- session.close();
- long end = System.currentTimeMillis();
- System.out.println((end-begin)/1000.0);
- }
- }
经过测试,花费时间为:148秒;
注:如果数据库在程序执行过程中记录数为0,是因为数据库为read commited,事务提交之后才能够数据。
当然,同样可以使用Hibernate配置来实现同样功能:
在hibernate.cfg.xml中插入:
- <property name="hibernate.jdbc.batch_size">50</property>//每50条语句提交一次
- <property name="hiberante.cache.use_second_level_cache">false</property>//关闭二级缓存