Spring + MyBatisの@Insertアノテーションでバルクインサートする方法

Spring + MyBatisの@Insertアノテーションでバルクインサートする方法

前提

Employeeテーブルのレコードは以下の通りとします。

ID NAME AGE
1 takahashi 20

Spring スタータープロジェクトで選択する依存関係は以下の通りとします。

Spring + MyBatisの@Selectアノテーションの使い方

@Mapperアノテーションを付与したインタフェースのメソッドに、@Insertアノテーションを付与します。

@InsertアノテーションにはSQL文を記述します。

従業員を表すPOJOです。

package jp.co.confrage.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
@AllArgsConstructor
public class Employee {
  private Long id;
  private String name;
  private Integer age;
}

従業員テーブルを操作するマッパーインタフェースです。@Insertアノテーション内に<script>タグを埋め、forEachタグを使用してバルクインサートを実装します。

package jp.co.confrage.repository;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface EmployeeMapper {
  @Insert({
  "<script>",
  "insert into employee (name,age) values ",
  "<foreach collection=\"data\" item=\"a\" separator=\",\"> ",
  "(",
  "#{a.name},",
  "#{a.age}",
  ")",
  "</foreach>",
  "</script>"
  })
  int bulkinsert(@Param("data") List<Employee> data);
}

@Mapperアノテーションを付与することで、DIが可能になります。

REST Controllerです。

package jp.co.confrage.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import jp.co.confrage.repository.EmployeeMapper;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
public class DemoController {
  private final EmployeeMapper employeeMapper;

  @GetMapping("/sample")
  public String sample() {
    final List<Employee> data = new LinkedList<>();
    data.add(new Employee(2L, "yamada", 20));
    data.add(new Employee(3L, "takagi", 30));
    data.add(new Employee(4L, "wada", 40));
    final var result = employeeMapper.bulkinsert(data);
    System.out.println(result); // insert件数
    return "sample";
  }
}

Spring Bootアプリケーションを起動し、curlコマンドを実行します。

curl -X GET http://localhost:8080/sample

以下が標準出力されます。

3

コメント

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました