java用hibernate向anywhere9中插入一百万条记录

表名:test,只有一个列id varchar(50);

 

hibernate.cfg.xml内容:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.SybaseDialect</property>

        //端口号可以通过双击服务图标查看,默认值为2638
        <property name="connection.url">jdbc:sybase:Tds:服务器IP地址:端口号/数据库名称</property>
        <property name="connection.username">用户名</property>
        <property name="connection.password">密码</property>
        <property name="connection.driver_class">com.sybase.jdbc3.jdbc.SybDataSource</property>
        <property name="myeclipse.connection.profile">test</property>
     <!--   -->

     //因为数据量大,会内存溢出,所以用下面语句定义50行提交一次
     <property name="hibernate.jdbc.batch_size">50</property>

     //关闭二级缓存,否则出错
  <property name="hibernate.cache.use_second_level_cache">false</property>

     <mapping resource="包名/表对应的类名.hbm.xml" />
    </session-factory>

</hibernate-configuration>

 

java程序:

import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class hibernateConnectAnywhere {
 public static void main(String[] args) {
  Date startDate = null;
  test tableTest = null;
  Transaction ts = null;
  Session session = HibernateSessionFactory.getSession();
  
  try {
   ts = session.beginTransaction();

   startDate = new Date();
   System.out.println("start time : "
     + (new SimpleDateFormat("HH:mm:ss").format(startDate)));
   
   for (int i = 0; i < 1000000; i++) {
    tableTest = new test();
    tableTest.setId("This is message" + i);
    session.save(tableTest);
    if ( i % 50 == 0 ) {//50行提交一次
              session.flush();
              session.clear();//清一级缓存,防止内存溢出
          }

   } 
   ts.commit();
  } catch (Exception e) {
   System.out.println(e.toString());
   ts.rollback();
  } finally {
   Date endDate = new Date();
   System.out.println("end time : "
     + (new SimpleDateFormat("HH:mm:ss").format(endDate)));
   System.out.println("spend time(sec.) : "
     + ((endDate.getTime() - startDate.getTime()) / 1000));

   session.close();
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值