Spring + MyBatisの@SelectKeyアノテーションでシーケンスオブジェクトのnextvalを取得する方法

Spring + MyBatisの@SelectKeyアノテーションでシーケンスオブジェクトのnextvalを取得する方法

前提

src/main/resources配下にschema.sqlを配置します。中身は以下の通りとします。(ID列はAUTO_INCREMENTしていること)

CREATE TABLE IF NOT EXISTS employee (
  id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(60) NOT NULL,
  age BIGINT NOT NULL
);
CREATE SEQUENCE IF NOT EXISTS SEQ_ID;

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

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

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

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

従業員を表すPOJOです。

package jp.co.confrage.entity;

import lombok.Getter;
import lombok.Setter;

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

従業員テーブルを操作するマッパーインタフェースです。

package jp.co.confrage.repository;

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

@Mapper
public interface EmployeeMapper {
  @Insert("insert into employee (id,name,age) values (#{autoId}, #{name}, #{age})")
  @SelectKey(
    statement = "select SEQ_ID.nextval ",
    keyProperty = "autoId",
    before = true,
    resultType = int.class)
  int insert(@Param("name") String name, @Param("age") Integer age);
}

@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 var count = employeeMapper.insert("yamada", 25);
    System.out.println(count);
    return "sample";
  }
}

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

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

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

1
MyBatis – MyBatis 3 | Java API

コメント

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

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

続きを読む

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