0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ポートフォリオ開発記】 #6 ユーザーコントローラーの作成

Posted at

はじめに

前回はUserServiceを実装しました!
今回はUserContollerを実装していきます!

Controller は Spring Boot アプリケーションにおける「リクエスト処理の窓口」ですね。

サービス層(UserService)やリポジトリ層(UserRepository)と連携しながら、
外部からの HTTP リクエストを処理していきます!

コード

package com.example.noteapp.backend.controller;

import com.example.noteapp.backend.entity.User;
import com.example.noteapp.backend.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        return ResponseEntity.ok(userService.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        return ResponseEntity.ok(userService.save(user));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteById(id);
        return ResponseEntity.noContent().build();
    }
} 

アノテーションの説明

アノテーション 説明
@RestController このクラスが REST API のコントローラーであることを示す。レスポンスは JSON。
@RequestMapping クラスのベースとなるパスを指定する。ここでは /api/users
@GetMapping HTTP GET リクエストを処理する。
@PostMapping HTTP POST リクエストを処理する。
@DeleteMapping HTTP DELETE リクエストを処理する。
@PathVariable URL のパスから変数部分を受け取る。例:/users/1id=1
@RequestBody リクエストの JSON ボディをオブジェクト(Userなど)に変換する。

コンストラクタ

public UserController(UserService userService) {
    this.userService = userService;
}

UserService を依存注入(DI)しています。

コントローラーでビジネスロジックを書くのではなく、Service に任せる構成にしています。

各メソッドの解説

getAllUsers()

@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
    return ResponseEntity.ok(userService.findAll());
}
  • 全ユーザーを取得して、200 OK とともに返す

getUserById(Long id)

@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
    return userService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
}
  • 指定された ID のユーザーを返す

  • ユーザーが存在しなければ 404 Not Found を返す

createUser(User user)

@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
    return ResponseEntity.ok(userService.save(user));
}
  • ユーザー情報を新規作成または更新

  • リクエストの JSON を User に変換して保存

deleteUser(Long id)

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
    userService.deleteById(id);
    return ResponseEntity.noContent().build();
}
  • 指定された ID のユーザーを削除

  • 削除に成功したら 204 No Content を返す

各層の関係

役割
Controller リクエストを受け取り、レスポンスを返す。Service に処理を委任。
Service ビジネスロジックを実装。リポジトリ層を操作。
Repository データベースアクセスを担当。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?