JPA를 이용한 RESTful API 작성

뚜우웅이·2023년 2월 6일
0

SpringBoot웹

목록 보기
4/23

REST API

BoardAPIController class를 생성해줍니다.

Spring.io에서 가져온 코드를 붙여넣고 수정해줍니다.

@RestController
class EmployeeController {

  private final EmployeeRepository repository;

  EmployeeController(EmployeeRepository repository) {
    this.repository = repository;
  }


  // Aggregate root
  // tag::get-aggregate-root[]
  @GetMapping("/employees")
  List<Employee> all() {
    return repository.findAll();
  }
  // end::get-aggregate-root[]

  @PostMapping("/employees")
  Employee newEmployee(@RequestBody Employee newEmployee) {
    return repository.save(newEmployee);
  }

  // Single item
  
  @GetMapping("/employees/{id}")
  Employee one(@PathVariable Long id) {
    
    return repository.findById(id)
      .orElseThrow(() -> new EmployeeNotFoundException(id));
  }

  @PutMapping("/employees/{id}")
  Employee replaceEmployee(@RequestBody Employee newEmployee, @PathVariable Long id) {
    
    return repository.findById(id)
      .map(employee -> {
        employee.setName(newEmployee.getName());
        employee.setRole(newEmployee.getRole());
        return repository.save(employee);
      })
      .orElseGet(() -> {
        newEmployee.setId(id);
        return repository.save(newEmployee);
      });
  }

  @DeleteMapping("/employees/{id}")
  void deleteEmployee(@PathVariable Long id) {
    repository.deleteById(id);
  }
}

가져온 코드의 변수명을 쉽게 바꾸기 위해서 Ctrl + r 키를 눌러서 Match Case 기능을 사용해줍니다.

수정된 코드

package com.project.myhome.controller;

import com.project.myhome.model.Board;
import com.project.myhome.repository.BoardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
class BoardAPIController {

    @Autowired
    private BoardRepository repository;

    @GetMapping("/boards")
    List<Board> all() {
        return repository.findAll();
    }
    // end::get-aggregate-root[]

    @PostMapping("/boards")
    Board newBoard(@RequestBody Board newBoard) {
        return repository.save(newBoard);
    }

    // Single item

    @GetMapping("/boards/{id}")
    Board one(@PathVariable Long id) {

        return repository.findById(id).orElse(null);
    }

    @PutMapping("/boards/{id}")
    Board replaceBoard(@RequestBody Board newBoard, @PathVariable Long id) {

        return repository.findById(id)
                .map(board -> {
                    board.setTitle(newBoard.getTitle());
                    board.setContent(newBoard.getContent());
                    return repository.save(board);
                })
                .orElseGet(() -> {
                    newBoard.setId(id);
                    return repository.save(newBoard);
                });
    }

    @DeleteMapping("/boards/{id}")
    void deleteBoard(@PathVariable Long id) {
        repository.deleteById(id);
    }
}

처음 GetMapping은 게시판 정보를 다 가져오는 것이고 id값을 사용하는 GetMapping은 게시판에 쓰여진 글을 확인하는 용도로 사용하는 것입니다.
PostMapping은 글을 수정할 때 사용합니다.
PutMapping은 글을 수정할 때 이미 id값이 존재하면 업데이트를 해주고 아닌 경우 삽입을 해주는 용도로 사용합니다.
DeleteMapping은 게시판의 글을 삭제하는 용도로 사용합니다.

http://localhost:8080/api/boards으로 들어가게 되면
GetMapping으로 repositoty findAll이 호출 되어 아래와 같이 게시판 데이터가 나옵니다.
나오는 형태는 JSON 형식입니다.

http://localhost:8080/api/boards/1
id값을 1로 주게 되면 1번 게시판의 내용을 가지고 오게됩니다.

제목이나 내용으로 검색하기

title이 전달이 됐으면 title로 검색을 하고 아니면 전체 데이터를 가져옵니다.
먼저 BoardRepositoty를 수정해줍니다.

package com.project.myhome.repository;

import com.project.myhome.model.Board;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface BoardRepository extends JpaRepository<Board, Long> {
    List<Board> findByTitle(String title);
    List<Board> findByTitleOrContent(String title, String content);
}

인터페이스를 정의만 하면 구현은 자동으로 됩니다.

BoardAPIController 수정

@GetMapping("/boards")
    List<Board> all(@RequestParam(required = false, defaultValue = "") String title,
        @RequestParam(required = false, defaultValue = "") String content) {
        if(StringUtils.isEmpty(title) && StringUtils.isEmpty(content)){
            return repository.findAll();
        }
        else{
            return repository.findByTitleOrContent(title, content);
        }
    }

http://localhost:8080/api/boards?title=제목 이런 방식으로 입력을 하게 되면
title 값에 맞는 데이터가 나옵니다.

title과 content에 값이 안 들어오면 default값인 빈문자열이 주어집니다.

http://localhost:8080/api/boards?title=제목&content=내용
으로 입력을 해도 위에 사진과 같은 데이터가 나옵니다.

REST API test

Postman을 다운받아 줍니다.

GetMapping test
먼저 GetMapping을 했을 때 나오는 JSON 형식의 데이터를 확인해줍니다.

PostMapping test
PostMapping test는 raw형태의 JSON으로 전달합니다.

위와 같이 body에 입력해서 전달을 하게 되면 데이터베이스에 값이 들어오는 것을 확인 할 수 있습니다.

PutMapping test
수정할 글의 id값을 입력하고 title을 수정합니다.

DeleteMapping
Body없이 id값만 전송을 해줍니다.

profile
공부하는 초보 개발자

0개의 댓글