0

爪哇代码:

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

我在这里有所有联系人的列表,我想以 100 个批量添加所有联系人。我使用的是休眠 4 和弹簧 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" />

我该如何进一步进行。谢谢你。

4

2 回答 2

1

JPA 本身不提供批量插入功能,但 hibernate 提供。我看到你已经有一个sessionFactory豆子了。因此,您可以按照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();
于 2013-01-02T07:00:25.487 回答
0

参考: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>

一起做这些事情你可以插入比以前的类型快得多。

于 2014-12-15T11:14:33.490 回答