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

时间:2013-12-08 20:06:49

标签: java 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=?

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

3 个答案:

答案 0 :(得分:27)

关于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

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

答案 1 :(得分:5)

在会话中使用save()方法,Hibernate将对象耦合到一行,并且在会话保持活动状态时此关系保持不变。因此,如果使用相同的对象,则实际更新现有行。解决方案是为每一行构造一个新对象。在这种情况下:

for (String item : items)
{
  Feature feature = new Feature();
  feature.setName(item);
  session.save(feature);
}

答案 2 :(得分:-1)

session.merge(object);
session.flush();
session.clear();
相关问题