プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

REST API × SpringBoot × MyBatis

RESTとはサーバ・クライアント間でデータをやりとりする為のソフトウェアアーキテクチャの1つである
 
今回はCRUD(※1)操作をHTTPメソッド(※2)を使ってクライアントに返す「REST API」について解説する
 
※1 CRUD

用語 内容 SQL
Create 登録 INSERT
Read 参照 SELECT
Update 変更 Read
Delete 削除 DELETE

 
※2 HTTPメソッド

HTTPメソッド 内容 CRUD
POST 登録 Create
GET 参照 SELECT
PUT 変更 Update
DELETE 削除 Delete

 
尚、O/RマッパーはMyBatisを使用する
設定方法は下記参照
 
MyBatis Generatorの設定方法と実行
 
 


■テーブル作成

今回は下記のテーブルを作成

create table sample (
    id int primary key auto_increment
    , name varchar(20)
    , age int
    );

 
※その他、DBの設定は下記を参考に設定
SpringBoot入門 vol.6:データベースの準備をしよう
 
 


■Rest APIのコントローラークラスを作成

・プロジェクト名
rest_sample
 
・格納場所
src/main/java/com/example/api/SampleController.java
 

package com.example.api;

import java.net.URI;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.example.domain.Sample;
import com.example.domain.SampleExample;
import com.example.mybatis.mapper.SampleMapper;

@RestController
@RequestMapping("api")
public class SampleController {
    @Autowired
    SampleMapper sampleMapper;

    @Autowired
    SampleExample sampleExample;

    /** POST:1件登録 */
    @PostMapping
    //@ResponseStatus(HttpStatus.CREATED)で「201 Created」を返す
    @ResponseStatus(HttpStatus.CREATED)
    //ResponseEntity<Sample>でLocationヘッダーにリソースURLを設定
    //@RequestBodyでSampleオブジェクトにマッピング
    //UriComponentsBuilderでURLを作成
    ResponseEntity<Sample> insertUser(@RequestBody Sample sample, UriComponentsBuilder uriBuilder) {
        //インサート処理
        sampleMapper.insert(sample);

        //URLを作成
        URI location = uriBuilder.path("api").buildAndExpand(sample.getId()).toUri();

        //HTTPレスポンスヘッダを設定する為にResponseEntityオブジェクトを返すと同時にLocationヘッダを設定
        return ResponseEntity.created(location).body(sample);
    }

    /** GET:全件取得 */
    @GetMapping()
    List<Sample> getList() {
        return sampleMapper.selectByExample(sampleExample);
    }

    /** GET:IDをキーに1件取得 */
    @GetMapping("{id}")
    Sample getUser(@PathVariable("id") Integer id) {
        return sampleMapper.selectByPrimaryKey(id);
    }

    /** PUT:IDをキーに1件更新 */
    @PutMapping("{id}")
    int updateUser(@PathVariable("id") Integer id, @RequestBody Sample sample) {
        sample.setId(id);

        //updateByPrimaryKeySelective()メソッドによってNullは更新しない
        return sampleMapper.updateByPrimaryKeySelective(sample);
    }

    /** DELETE:IDをキーに1件削除 */
    @DeleteMapping("{id}")
    int deleteUser(@PathVariable("id") Integer id) {
        return sampleMapper.deleteByPrimaryKey(id);
    }
}

 
 


■CurlでHTTPメソッドを実行

Curlコマンドのオプションは下記参照
Curlコマンド
 
 

POST(登録)

curl http://localhost:8080/api -i -XPOST -H "Content-Type:application/json" -d "{\"name\":\"tanaka\", \"age\":\"20\"}"

 

GET(参照)

#全レコード参照
curl http://localhost:8080/api -i -XGET

#ID:1のレコードを参照
curl http://localhost:8080/api/1 -i -XGET

 

PUT(変更)

#ID:1のレコードを変更
curl http://localhost:8080/api/1 -i -XPUT -H "Content-Type:application/json" -d "{\"name\":\"tanaka\", \"age\":\"40\"}"

#ID:1のレコードのage項目のみ変更
curl http://localhost:8080/api/1 -i -XPUT -H "Content-Type:application/json" -d "{\"age\":\"25\"}"

 

DELETE(削除)

#ID:1のレコードを削除
curl http://localhost:8080/api/1 -i -XDELETE