[ Baeldung ] Batch Insert/Update with Hibernate/JPA
[ Medium ] Boost JPA Bulk Insert Performance by 90% (Postgresql)
Spring Data Jpa 이용하여 Batch Insert 하기
Yaml 파일 설정
spring: jpa: open-in-view: false show-sql: true hibernate: ddl-auto: none # test/resources/schema-mssql.sql 을 이용하여 ddl 실행 properties: hibernate: format_sql: true jdbc: batch_size: 50 order_inserts: true
Entity의 @GeneratedValue
를 Identity가 아닌 SEQUENCE 혹은 TABLE로 변경 필요함
@Entity @NoArgsConstructor(access = AccessLevel.PROTECTED) @SequenceGenerator( name = "ACCOUNT_SEQ_GENERATOR", sequenceName = "account_seq", initialValue = 100001, allocationSize = 1 ) @Getter @Table(name = "accounts") public class Account extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ACCOUNT_SEQ_GENERATOR") private Integer id;
Batch 가 잘 되고 있는지 확인하기 위하여 Yaml 파일에 로깅 레벨 변경(BatchingBatch
)
logging: level: org.hibernate.engine.jdbc.batch.internal.BatchingBatch: debug ## 2023-05-11 10:53:52.889 DEBUG --- [Test worker] o.h.e.j.batch.internal.BatchingBatch : Executing batch size: 100
신기했던 점들
- BatchSize를 몇으로 하건간에, Hibernate 의 show-sql: true로 해서 나오는 로그는 insert 구문이 한 개씩 찍힘.(되게 헷갈리게시리)
- Hibernate에서 Batching은 내부적 로직(JDBC level optimization)에서 작동하기 때문에(behind the scenes), Hibernate level에서는 Batch가 되고 있다는 것을 알수가 없음 [참고 : Hibernate batching explained ]
- 본 글에서 추천하는 로 로깅을 하던가 위의 BatchingBatch로 배치 갯수 로그 확인 가능함
- 또한, BatchSize의 개수에 상관없이 넣을 전체의 id 값을 다 불러온 뒤 insert를 실행함(GenerationType.SEQUENCE 일 때)
Hibernate: select next value for account_seq Hibernate: select next value for account_seq Hibernate: select next value for account_seq Hibernate: select next value for account_seq ...