繁体   English   中英

使用Hibernate 4和Spring 3.x批量插入记录

[英]insert records in batch using hibernate 4 and spring 3.x

Java代码:

EntityManager em1 = entityService.getEntityManager();
Query qury1 = em1.createNamedQuery(Constants.UNPROCESSED_CONTACTS);
List<Contact> contacts =  entityService.findByNamedQuery(qury1);

我在这里有所有联系人的列表,我想批量添加所有联系人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" />

我该如何进一步。 感谢在广告中

JPA本身不提供批处理插入功能,但是hibernate提供。 我看到您已经有一个sessionFactory bean。 因此,您可以按照休眠文档中的示例进行操作:

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();

参考: https : //docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html

对于批量插入:

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();

并在休眠XML配置中:

<entry key="hibernate.jdbc.batch_size">50</entry>

一起做这些事情,您可以比以前的类型更快地插入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM