Hibernate入门:批量插入数据
来源:互联网 发布:python logger.debug 编辑:程序博客网 时间:2024/05/22 14:59
一般如果要插入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{@Testpublic 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{@Testpublic 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>//关闭二级缓存
- Hibernate入门:批量插入数据
- Hibernate入门:批量插入数据
- hibernate批量插入数据
- Hibernate批量插入数据
- hibernate批量插入数据
- hibernate批量数据插入优化
- Hibernate中,数据批量插入
- Hibernate 批量插入数据方法
- Hibernate 批量插入数据,跳过重复数据
- Hibernate 数据的批量插入等
- hibernate 批量插入数据时 内存溢出
- hibernate 使用jdbc批量插入数据
- hibernate入门--实现数据简单插入
- hibernate批量插入思路
- Hibernate 批量插入
- hibernate批量插入
- Hibernate批量插入
- hibernate 批量插入
- Android系统手机端抓包方法
- Oracle SQL性能优化技巧大总结
- java 操作数组的工具类
- 设计模式之观察者模式
- Shopex 4.8.5 SQL Injection Exp
- Hibernate入门:批量插入数据
- apache 反向代理
- VisionMobile:虚拟助手(VA)- Siri背后的前沿UI技术(五)
- 面试经验总结
- Oracle中组合索引的使用详解
- Android OpenGL ES 分析与实践
- android换肤功能实现(apk方式)
- DeDeCMS v5.7最新利用工具[一键暴密码]0day
- ext中xtype对照表