java – 如何使用hibernate将多行插入数据库?

栏目: Hibernate · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/20458401/how-to-insert-multiple-rows-into-database-using-hibernate

我正在循环列表并插入数据库,但它逐个更新记录.最后我只在数据库的最后一个记录中看到了这一点.

输入名称:Linux,windows,mac

Session session = (Session) HibernateUtil.getSessionFactory().openSession();
String[] items = pi.getNewLicenseName().split(",");
for (String item : items)
{
feature.setName(item);
session.save(feature);
}
 session.getTransaction().commit();
 HibernateUtil.shutdown();

hibernate.cfg.xml中:

<hibernate-configuration>

    <session-factory>


    <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="connection.url">jdbc:sqlserver://******</property>
    <property name="connection.username">*****</property>
    <property name="connection.password">*****</property>

    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>


        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>


        <property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Names the annotated entity class -->

         <mapping class="com.DAO.Feature"/>

    </session-factory>

这里三次得到循环并插入数据库.但以某种方式覆盖了值.因为我看到sql insert和update在控制台中运行.

Hibernate: insert into FEATURE (NAME) values (?)
Hibernate: update FEATURE set NAME=? where FEATURE_ID=?

请帮我把多行插入数据库.

关于 batch processing in the Hibernate docs

有一个非常好的章节.

设置属性

hibernate.jdbc.batch_size 20

然后使用此代码

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

tx.commit();
session.close();

请务必考虑对您的ID生成策略的影响,例如 discussed here .

更新2015-09-23

我终于找到了坐下来在 http://frightanic.com/software-development/jpa-batch-inserts/ 写一篇详细文章的时间.

翻译自:https://stackoverflow.com/questions/20458401/how-to-insert-multiple-rows-into-database-using-hibernate


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

创新公司

创新公司

[美]艾德·卡特姆、埃米·华莱士 / 靳婷婷 / 中信出版社 / 2015-2 / 49.00元

●《玩具总动员》《海底总动员》《机器人瓦力》《飞屋环游记》等14部脍炙人口的动画长片, 近30次奥斯卡奖, 7部奥斯卡最佳动画长片,7次金球奖; ●几乎每一部电影一上映都位居票房榜首,所有电影都曾进入影史票房总榜前50,每一部电影都是商业与艺术的双赢。 ●即便新兴动画公司不断涌现,皮克斯始终保持动画界的王者之位,这一切背后的秘密就在于:不断推动创新的创意管理方式。 你可以从本书......一起来看看 《创新公司》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具