Spring + MyBatisの@Insertアノテーションの使い方
前提
Employeeテーブルのレコードは以下の通りとします。
| ID | NAME | AGE |
|---|---|---|
| 1 | takahashi | 20 |
src/main/resources/配下のschema.sqlは以下の通りです。
CREATE TABLE IF NOT EXISTS employee ( id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(60) NOT NULL, age BIGINT NOT NULL );
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;
@Mapper
public interface EmployeeMapper {
@Insert("insert into employee (name,age) values (#{name}, #{age})")
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); // insert件数
return "sample";
}
}
Spring Bootアプリケーションを起動し、curlコマンドを実行します。
curl -X GET http://localhost:8080/sample
以下が標準出力されます。
1
テーブル定義のidがauto incrementなのでidは省略すればinsertが正常に実行されます。
auto incrementではない場合は、@Optionsや@SelectKeyアノテーションを付与してサロゲートキーを採番する必要があります。

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



コメント