[UMC Server] 6주차 - CRUD API

서요이·2022년 11월 16일
0

UMC Server

목록 보기
6/7
  1. 게시판 CRUD를 할 수 있는 API 개발
  2. API 명세서 작성

1. 게시판 CRUD를 할 수 있는 API 개발

1) spring initializr로 프로젝트 시작

start.spring.io 에서 원하는 의존성을 추가하여 초기 설정된 스프링 부트 프로젝트 생성

  • Dependency
    • Lombok: 반복적인 개발을 줄일 수 있는 여러 기능을 제공하는 자바 라이브러리
    • Spring Web: HTTP 클라이언트와 Spring의 원격 지원을 위한 웹 관련 부분 제공
    • Spring Data JPA: JPA 기반 repository를 쉽게 만들 수 있도록 다양한 기능 제공
    • MySQL Driver: MySQL 데이터베이스에 접근하기 위한 드라이버

2) 데이터베이스 생성

MySQL 터미널 접속

mysql> create database carrot;
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| carrot             |
| information_schema |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+

carrot 데이터베이스 생성

3) 데이터베이스 연결

application.yml파일에 데이터베이스 접속 정보 입력

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/carrot
    username: root
    password: password
  jpa:
    hibernate:
      ddl-auto: create
  • 속성값
    • spring.datasource.url: MySQL의 호스트 이름, 데이터베이스
    • spring.datasource.username: MySQL username
    • spring.datasource.password: MySQL password
    • spring.jpa.hibernate.ddl-auto: 데이터베이스 초기화 옵션

Database 탭에서 MySQL 연결

package com.umc.carrot;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test")
    public String test() {
        return "hello world";
    }
}

TestController 작성

Run → localhost:8080/test 로 접속해 제대로 실행되는지 확인

4) CRUD API 구현

  • 프로젝트 구조

    • Entity
      User.java
    • Controller
      UserController.java
    • Repository
      UserRepository.interface
    • Service
      UserService.java
    • Main Application
      CarrotApplication.java
  • API

    MethodURIDescription
    POST/user회원 가입
    GET/user전체 유저 조회
    GET/user/{id}특정 유저 조회
    POST/user/{id}/update유저 정보 변경
    POST/user/{id}/delete유저 정보 삭제
  • User.java

    package com.umc.carrot.entity;
    
    import lombok.Builder;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
    import lombok.Setter;
    
    import javax.persistence.*;
    
    @Entity
    @Getter
    @NoArgsConstructor
    public class User {
    
        @Id
        @GeneratedValue (strategy = GenerationType.IDENTITY)
        private Long id;
    
        @Column(nullable = false)
        private String name;
    
        @Column(nullable = false)
        private int age;
    
        private String address;
    
        @Builder
        public User(String name, int age, String address){
            this.name = name;
            this.age = age;
            this.address = address;
        }
    
        public void update(String name, int age, String address) {
            this.name = name;
            this.age = age;
            this.address = address;
        }
    }
  • UserRepository.java

    package com.umc.carrot.repository;
    
    import com.umc.carrot.entity.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository<User, Long> {
    }
  • UserService.java

    package com.umc.carrot.service;
    
    import com.umc.carrot.entity.User;
    import com.umc.carrot.repository.UserRepository;
    import lombok.RequiredArgsConstructor;
    import org.springframework.stereotype.Service;
    
    import javax.transaction.Transactional;
    
    @RequiredArgsConstructor
    @Service
    public class UserService {
    
        public final UserRepository userRepository;
    
        public User findById(Long id) {
            return userRepository.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 유저입니다."));
        }
    
        @Transactional
        public Long save(User user) {
            return userRepository.save(user).getId();
        }
    
        @Transactional
        public Long update(Long id, User user) {
            User currentUser = findById(id);
            currentUser.update(user.getName(), user.getAge(), user.getAddress());
            return id;
        }
    
        @Transactional
        public void delete(Long id) {
            User user = findById(id);
            userRepository.delete(user);
        }
    }
  • UserController.java

    package com.umc.carrot.controller;
    
    import com.umc.carrot.entity.User;
    import com.umc.carrot.service.UserService;
    import lombok.RequiredArgsConstructor;
    import org.springframework.web.bind.annotation.*;
    
    @RequiredArgsConstructor
    @RestController
    public class UserController {
    
        private final UserService userService;
    
        @PostMapping("/user")
        public Long create(@RequestBody User user) {
            return userService.save(user);
        }
    
        @GetMapping("/user/{id}")
        public User read(@PathVariable Long id) {
            return userService.findById(id);
        }
    
        @PostMapping("/user/{id}/update")
        public Long update(@PathVariable Long id, @RequestBody User user) {
            return userService.update(id, user);
        }
    
        @PostMapping("/user/{id}/delete")
        public Long delete(@PathVariable Long id) {
            userService.delete(id);
            return id;
        }
    }

5) Postman으로 API 테스트

Postman - My Workspace - New Request

POST 실행 시 unsupported media type error 발생

  • 트러블 슈팅
    [ 문제 원인 ]
    input data 값 타입 지원 X
    [ 해결 방안 ]
    Header > Content-Type: application/json 추가 [ 참고 자료 ] https://injekim97.tistory.com/627

Create 성공 (id 값 반환)

Read 성공

Update 성공

Delete 성공

2. API 명세서 작성

0개의 댓글