배치 업데이트(Batch Update)

2024. 5. 17. 09:26Back-End/Spring

배치 업데이트(Batch Update)는 데이터베이스와 연동되는 애플리케이션에서 한 번에 다수의 레코드를 처리할 때 매우 유용한 방법이다. 이를 통해 성능을 최적화하고, 네트워크 트래픽을 줄일 수 있다. 이번 글에서는 스프링 프레임워크를 사용하여 배치 업데이트를 구현하는 방법을 소개하고, 이를 예제 코드를 통해 설명하고자 한다.

 

배치 업데이트란?

배치 업데이트는 데이터베이스에 다수의 데이터를 일괄적으로 업데이트하는 작업을 말한다. 여러 개의 SQL 문을 하나의 배치로 묶어 데이터베이스에 한 번에 전송함으로써, 데이터베이스와의 통신 횟수를 줄이고, 각 SQL 문을 개별적으로 실행할 때 발생할 수 있는 오버헤드를 줄일 수 있다.

 

스프링에서의 배치 업데이트

스프링 프레임워크에서는 JdbcTemplate을 사용하여 배치 업데이트를 쉽게 구현할 수 있다. JdbcTemplate은 JDBC를 더 간편하게 사용할 수 있게 해주는 스프링의 유틸리티 클래스이다. 이를 통해 배치 업데이트를 수행하는 방법을 알아보자.

 

예제 코드

아래는 CommandLineRunner를 사용하여 애플리케이션 시작 시 배치 업데이트를 수행하는 예제 코드이다.

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

@SpringBootApplication
public class Springdatajdbc01Application {

    public static void main(String[] args) {
        SpringApplication.run(Springdatajdbc01Application.class, args);
    }

    @Bean
    public CommandLineRunner batchUpdateDemo(JdbcTemplate jdbcTemplate) {
        return args -> {
            List<User> users = Arrays.asList(
                    new User(null, "Alice", "alice@example.com"),
                    new User(null, "Bob", "bob@example.com"),
                    new User(null, "Charlie", "charlie@example.com"),
                    new User(null, "David", "david@example.com")
            );

            String sql = "INSERT INTO users (name, email) VALUES (?, ?)";

            // Execute batch update
            int[] updateCounts = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    User user = users.get(i);
                    ps.setString(1, user.getName());
                    ps.setString(2, user.getEmail());
                }

                public int getBatchSize() {
                    return users.size();
                }
            });

            System.out.println("Batch update completed. Number of rows affected: " + Arrays.toString(updateCounts));
        };
    }
}

코드 설명

  1. Springdatajdbc01Application 클래스:
    - 스프링 부트 애플리케이션의 진입점이다.
    - CommandLineRunner를 빈으로 정의하여 애플리케이션 시작 시 특정 작업을 수행하도록 설정한다.

  2. batchUpdateDemo 메서드:
    - JdbcTemplate을 매개변수로 받아, 배치 업데이트를 수행한다.
    - 여러 User 객체를 포함하는 리스트를 생성한다.

  3. SQL 문:
    - INSERT INTO user(name, email) VALUES(?, ?)라는 SQL 문을 사용하여 사용자를 데이터베이스에 삽입한다.

  4. BatchPreparedStatementSetter 인터페이스:
    - setValues 메서드는 각 사용자에 대한 값을 설정한다.
    - getBatchSize 메서드는 배치 크기를 반환한다.

  5. 배치 업데이트 실행:
    - jdbcTemplate.batchUpdate 메서드를 호출하여 배치 업데이트를 수행한다.
    - 업데이트된 행의 수를 출력한다.

결론

배치 업데이트는 대량의 데이터를 효율적으로 처리할 있는 강력한 방법이다. 이를 통해 성능을 최적화하고 네트워크 트래픽을 줄일 있으며, 트랜잭션 관리도 용이해진다. 스프링 프레임워크를 사용하면 JdbcTemplate 통해 배치 업데이트를 쉽게 구현할 있다. 대량 데이터 처리 작업이 필요한 경우, 배치 업데이트를 적극 활용해 보기를 권장한다.

'Back-End > Spring' 카테고리의 다른 글

ResultSetExtractor  (0) 2024.05.17
@Transactional과 TransactionTemplate  (0) 2024.05.17
Spring Data JDBC  (0) 2024.05.16
@Configuration 및 @Bean vs @ComponentScan  (0) 2024.05.14
IoC와 DI  (0) 2024.05.14