我正在循环列表并插入数据库,但它会一条一条地更新记录。最后我在数据库中看到的只是列表的最后一条记录。
输入名称: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 插入和更新在控制台中运行。
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
我终于抽出时间坐下来在 https://frightanic.com/software-development/jpa-batch-inserts/ 上写一篇详细的文章.
关于java - 如何使用 hibernate 将多行插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20458401/