0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring transactionメモ

Last updated at Posted at 2024-02-07
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.io.IOException;

@Service
public class CsvImportService {

    private final JdbcTemplate jdbcTemplate;
    private final PlatformTransactionManager transactionManager;

    @Autowired
    public CsvImportService(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
        this.jdbcTemplate = jdbcTemplate;
        this.transactionManager = transactionManager;
    }

    @Transactional
    public int importCsvData(String tableName, String csvFilePath) {
        try {
            // トランザクションを開始
            TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());

            try {
                // CSVファイルからデータを読み込み、データベースに一括挿入
                String copySql = "COPY " + tableName + " FROM '" + csvFilePath + "' WITH CSV HEADER";
                jdbcTemplate.execute(copySql);

                // トランザクションをコミット
                transactionManager.commit(status);

                return 0; // 正常終了
            } catch (Exception e) {
                // エラーが発生した場合、トランザクションをロールバック
                transactionManager.rollback(status);
                e.printStackTrace();
                return 1; // 異常終了

                // SQLExceptionに変換してスローし、トランザクションをロールバック
                //throw new RuntimeException("データベースエラー", e);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 1; // 異常終了
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?