[英]insert records in batch using hibernate 4 and spring 3.x
java code: Java代码:
EntityManager em1 = entityService.getEntityManager();
Query qury1 = em1.createNamedQuery(Constants.UNPROCESSED_CONTACTS);
List<Contact> contacts = entityService.findByNamedQuery(qury1);
i have list of all contacts here , and i would like to add all contacts in batch of 100. i am using hibernate 4 and spring 3.1 my applicationContext is 我在这里有所有联系人的列表,我想批量添加所有联系人100。我正在使用hibernate 4和spring 3.1我的applicationContext是
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
how can i proceed further. 我该如何进一步。 thanks in adv.
感谢在广告中
JPA itself doesn't provide a batch insert facility, but hibernate does. JPA本身不提供批处理插入功能,但是hibernate提供。 I see you already have a
sessionFactory
bean. 我看到您已经有一个
sessionFactory
bean。 So you can just follow the example in the hibernate docs : 因此,您可以按照休眠文档中的示例进行操作:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
ScrollableResults customers = session.getNamedQuery("GetCustomers")
.setCacheMode(CacheMode.IGNORE)
.scroll(ScrollMode.FORWARD_ONLY);
int count=0;
while ( customers.next() ) {
Customer customer = (Customer) customers.get(0);
customer.updateStuff(...);
if ( ++count % 20 == 0 ) {
//flush a batch of updates and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
Ref: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html 参考: https : //docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html
For Bulk Insert: 对于批量插入:
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();
And in hibernate XML configuration: 并在休眠XML配置中:
<entry key="hibernate.jdbc.batch_size">50</entry>
Do these thing together you can insert much faster than previous type. 一起做这些事情,您可以比以前的类型更快地插入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.