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" />我如何才能继续下去。在adv中谢谢。
发布于 2013-01-02 15:00:25
JPA本身不提供批插入功能,但hibernate提供了。我看到您已经有了一个sessionFactory bean。因此您只需遵循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();发布于 2014-12-15 19:14:33
参考: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();和在hibernate XML配置中:
<entry key="hibernate.jdbc.batch_size">50</entry>一起做这些事情,你可以比以前的类型更快地插入。
https://stackoverflow.com/questions/14117956
复制相似问题