[JAVA] 배치와 트랜잭션 [2]

박형석·2023년 5월 30일
0

배치와 트랜잭션 예제 코드

배치 처리란?

배치 처리는 대량의 데이터를 지정된 프로세스에 따라 일괄적으로 처리하는 방식입니다. 이를 통해 반복적이고 지속적인 작업을 자동화하고 효율적으로 처리할 수 있습니다. 자바에서는 java.util.concurrent 패키지와 java.util.stream 패키지 등을 활용하여 배치 처리를 구현할 수 있습니다.

트랜잭션 처리란?

트랜잭션은 데이터베이스의 상태를 변화시키기 위한 일련의 작업들을 모두 성공적으로 수행하거나, 그렇지 않은 경우 이전 상태로 롤백하는 것을 말합니다. 트랜잭션을 사용하여 데이터의 일관성과 안전성을 보장할 수 있습니다. 자바에서는 java.sql.Connection과 java.sql.DriverManager 클래스를 사용하여 트랜잭션 처리를 구현할 수 있습니다.

이제 배치와 트랜잭션을 함께 다루는 예제 코드를 살펴보겠습니다.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BatchTransactionExample {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
    private static final String DB_USER = "username";
    private static final String DB_PASSWORD = "password";

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            connection.setAutoCommit(false); // 트랜잭션 시작

            String insertQuery = "INSERT INTO users (name, email) VALUES (?, ?)";
            statement = connection.prepareStatement(insertQuery);

            // 배치 처리를 위한 데이터 추가
            statement.setString(1, "John");
            statement.setString(2, "john@example.com");
            statement.addBatch();

            statement.setString(1, "Jane");
            statement.setString(2, "jane@example.com");
            statement.addBatch();

            // 배치 처리 실행
            int[] result = statement.executeBatch();
            connection.commit(); // 트랜잭션 커밋

            System.out.println("배치 처리 완료!");

        } catch (SQLException e) {
            if (connection != null) {
                try {
                    connection.rollback(); // 트랜잭션 롤백
                } catch (SQLException rollbackEx) {
                    rollbackEx.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException statementEx) {
                    statementEx.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException connectionEx) {
                    connectionEx.printStackTrace();
                }
            }
        }
    }
}

위의 예제 코드는 자바를 사용하여 배치 처리와 트랜잭션을 구현하는 방법을 보여줍니다. 코드에서는 MySQL 데이터베이스를 사용하고 있으며, users 테이블에 레코드를 배치 처리하여 추가합니다.

addBatch() 메서드를 사용하여 배치 처리를 위한 데이터를 추가하고, executeBatch() 메서드를 호출하여 배치 작업을 실행합니다. 트랜잭션은 connection.setAutoCommit(false)를 호출하여 수동으로 시작하고, 성공적으로 처리되면 connection.commit()으로 커밋합니다. 예외가 발생하는 경우 connection.rollback()을 호출하여 트랜잭션을 롤백합니다.

위의 예제 코드는 단순한 예제일 뿐이며, 실제 상황에 따라 추가적인 예외 처리와 로직이 필요할 수 있습니다. 배치 처리와 트랜잭션을 사용할 때는 데이터베이스 및 프레임워크의 지원을 확인하고, 보다 안정적인 코드를 작성해야 합니다.

profile
Better Than Yesterday

0개의 댓글