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

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

前提

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

ID NAME AGE
1 takahashi 20

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

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

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

@Selectアノテーションには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 java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import jp.co.confrage.entity.Employee;

@Mapper
public interface EmployeeMapper {

  @Select("select * from employee")
  List<Employee> selectAll();
}

@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 result = employeeMapper.selectAll();
    result
      .stream()
      .forEach(
        e -> {
          System.out.println(e.getId()); // DBにレコードあれば出力される
          System.out.println(e.getName()); // DBにレコードあれば出力される
          System.out.println(e.getAge()); // DBにレコードあれば出力される
        });
    return "sample";
  }
}

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

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

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

1
takahashi
20

org.apache.ibatis.annotations.Param

select文でwhere句を指定したい場合にパラメータを渡す場合は@Paramで渡します。

selectByIdメソッドでidをパラメータで渡す例です。

@Select("select * from employee whrere id=#{id}")
Employee selectById(@Param("id") Integer id);

#{xxx}とすることによってSQLインジェクションを防ぎます。

コメント

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

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

続きを読む

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