2017-09-04 4 views
0

私はSpringブートアプリケーションを持っています。 application.ymlで :SpringデータのsaveAll()メソッドとHibernate 5バッチを使用できますか?

spring: 
    datasource: 
     driver-class-name: org.postgresql.Driver 
     url: *my_url* 
     password: *my_pass* 
     username: *my_username* 
    jpa: 
     properties: 
      hibernate: 
       jdbc: 
        batch_size: 15 
        #order_inserts: true 
        #order_updates: true 
        #batch_versioned_data: true 

私は方法SAVEALL(反復処理可能エンティティ)を使用して200個の000エンティティを保存しようとすると、それは同時に、すべての200個の000のエンティティを保存するが、私は15個のエンティティ

でバッチを保存したいです

SpringデータSimpleJpaRepositoryとHibernateバッチを使用することはできますか?

+0

https://frightanic.com/software-development/jpa-batch-inserts/ – Cepr0

+0

作業しますか? – 11thdimension

+0

@ Cepr0、ちょっと古いのですか? – 11thdimension

答えて

1

私のアプローチは))

@Service 
public class BulkService { 

    @PersistenceContext 
    private EntityManager em; 

    // @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}") 
    private int batchSize = 20; 

    private List<Entity> savedEntities; 

    public Collection<Entity> bulkSave(List<Entity> entities) { 
     int size = entities.size(); 
     savedEntities = new ArrayList<>(size); 

     try { 
      for (int i = 0; i < size; i += batchSize) { 
       int toIndex = i + (((i + batchSize) < size) ? batchSize : size - i); 
       processBatch(entities.subList(i, toIndex)); 
       em.flush(); 
       em.clear(); 
      } 
     } catch (Exception ignored) { 
      // or do something... 
     } 
     return savedEntities; 
    } 

    @Transactional 
    protected void processBatch(List<Entity> batch) { 

     for (Entity t : batch) { 
      Entity result; 
      if (t.getId() == null) { 
       em.persist(t); 
       result = t; 
      } else { 
       result = em.merge(t); 
      } 
      savedEntities.add(result); 
     } 
    } 
} 

exampleおよび使用している春データのバージョンtest

関連する問題