【 Spring Boot】@RequestMappingや@GetMapping等の違いと役割について

【 Spring Boot】@RequestMappingや@GetMapping等の違いと役割について バックエンド
スポンサーリンク

はじめに

ぴんくうさぎ
ぴんくうさぎ

Spring Bootで開発を始めたのだけど、
controllerに書く@GetMappingとか@PostMappping
の違いがよくわからない!

みどりがめ
みどりがめ

Mapping系のアノテーションだね!
よし、今回はGetやPost以外にも代表的なものの
違いを見ていくよ!

この記事では、Spring Bootによる開発では欠かせないMapping系統のアノテーションについて解説します。
代表的なものとして@RequestMapping、@GetMapping、@PostMapping、@PutMapping、@DeleteMappingがありますが、いずれも共通する点としてURLとコントローラーのクラスやメソッドを紐づける役割を担います。本記事でそれぞれの違い、特徴をしっかり理解しましょう。

前提

初めに本記事で使用するサンプルコードを掲載します!
あくまでMapping系のアノテーションの説明がテーマなので、説明に必要なControllerクラスのみとさせていただいております。また、全部読まなくても問題ございません。赤字の部分に着目してください。
以降で赤文字部分の①〜⑤について解説します。

@RestController
@RequestMapping("/api-sample") //・・・①
public class ApiSampleController {

    @Autowired
    ApiSampleService apiSampleService;

    @GetMapping("/{id}") //・・・②
    public ResponseEntity<ApiSampleModel> searchTopicById(@PathVariable Integer id){
        ApiSampleModel model=  apiSampleService.findById(id);
        return ResponseEntity.ok(model);
    }

    @PostMapping("/createTopic") //・・・
    public ResponseEntity<ApiSampleModel> createTopic(@RequestBody ApiSampleForm form){
        ApiSampleModel model = apiSampleService.addTopic(form.getTitle(),form.getContent());
        return  ResponseEntity.status(HttpStatus.CREATED).body(model);
    }

    @PutMapping("/{id}") //・・・
    public ResponseEntity<ApiSampleModel> editTopic(@PathVariable Integer id,@RequestBody ApiSampleForm form){
        ApiSampleModel model = apiSampleService.updateTopic(id,form.getTitle(), form.getContent());
        return ResponseEntity.ok(model);
    }

    @DeleteMapping("/{id}") //・・・
    public ResponseEntity<Void> deleteTopic(@PathVariable Integer id){
        ApiSampleModel model = apiSampleService.deleteTopic(id);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}

@RequestMapping

@RequestMappingは主にクラスとクラスパスを紐づける役割を担います。
赤文字のRequestMappingを記載することでこのクラスへのリクリクエストのURLは「http://ドメイン/api-sample/○○○」となります。

@GetMapping

@GetMappingメソッドとGETの処理を行うURLを紐づける役割を担います。
GETは「データの取得」として捉えておくとのちほどのPOSTやPUTとの違いもスムーズになります。

サンプルコードのgetメソッドは以下のようになっています。
リクエストとしては「http://ドメイン/api-sample/5」のようになりますね。
メソッド内でidが5のトピックをデータベースから取ってくるよりが書かれています(青文字)

    @GetMapping("/{id}") //・・・②
    public ResponseEntity<ApiSampleModel> searchTopicById(@PathVariable Integer id){
        ApiSampleModel model=  apiSampleService.findById(id);
        return ResponseEntity.ok(model);
    }

@PostMapping

@PostMappingメソッドとPOSTの処理を行うURLを紐づける役割を担います。
POSTは「データの登録」として理解すると良いでしょう。会員登録フォームから情報を入力して、DBに登録する際に利用します。

サンプルコードのpostメソッドは以下のようになっています。
リクエストとしては「http://ドメイン/api-sample/createTopic」になりますね。
引数のフォームの情報をもとにDBに新規登録する処理が記載されています(青文字)。

    @PostMapping("/createTopic") //・・・③
    public ResponseEntity<ApiSampleModel> createTopic(@RequestBody ApiSampleForm form){
        ApiSampleModel model = apiSampleService.addTopic(form.getTitle(),form.getContent());
        return  ResponseEntity.status(HttpStatus.CREATED).body(model);
    }

@PutMapping

@PutMappingメソッドとPUTの処理を行うURLを紐づける役割を担います。
PUTは「データの更新」として理解すると良いでしょう。もともと存在するデータを書き換える時に使用します。

サンプルコードのputメソッドは以下のようになっています。
リクエストとしては「http://ドメイン/api-sample/3」のようになりますね。
引数のidのトピックをフォームの情報をもとに更新する処理が記載されています(青文字)

   @PutMapping("/{id}") //・・・④
    public ResponseEntity<ApiSampleModel> editTopic(@PathVariable Integer id,@RequestBody ApiSampleForm form){
        ApiSampleModel model = apiSampleService.updateTopic(id,form.getTitle(), form.getContent());
        return ResponseEntity.ok(model);
    }

@DeleteMapping

@DeleteMappingメソッドとDeleteの処理を行うURLを紐づける役割を担います。
Deleteは「データの削除」になります。

サンプルコードのdeleteメソッドは以下のようになっています。
リクエストとしては「http://ドメイン/api-sample/5」のようになりますね。
メソッド内でidが5のトピックを削除する処理が書かれています青文字

    @DeleteMapping("/{id}") //・・・⑤
    public ResponseEntity<Void> deleteTopic(@PathVariable Integer id){
        ApiSampleModel model = apiSampleService.deleteTopic(id);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

終わりに

本記事はここまでとなります。
本記事で記載しているサンプルコードについては、下記の記事で詳しく解説しています。
もしよろしければ合わせてご覧ください。

最後にSpring学習のおすすめ教材を紹介します。
多くの方に支持されている人気商品です。気になる方は是非一度、覗いてみてください。

ご覧いただきありがとうございました。ご指摘等がございましたら頂けますと嬉しいです。
引き続き、プログラミングについて定期的に発信していきますのでよろしくお願いします!
また、もしよろしければtwitterもフォローしていただけると嬉しいです!🐢

コメント