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 スタータープロジェクトで選択する依存関係は以下の通りとします。
@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 3 | Java API – mybatis

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^



コメント