guide에서 카피 해오기

 

https://spring.io/guides/tutorials/rest/

 

Building REST services with Spring

this tutorial is designed to be completed in 2-3 hours, it provides deeper, in-context explorations of enterprise application development topics, leaving you ready to implement real-world solutions.

spring.io

 

 

 

 

BoardApiController.java

package com.toy.board.web;

import java.util.List;

import com.toy.board.domain.Board;
import com.toy.board.reopsitory.BoardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

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


    @Autowired
    private BoardRepository boardRepository;



    @GetMapping("/board")
    List<Board> all() {
        return boardRepository.findAll();
    }


    @PostMapping("/board")
    Board newBoard(@RequestBody Board newBoard) {
        return boardRepository.save(newBoard);
    }

    // Single item

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

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

    @GetMapping("/boards")
    List<Board> findByTitle(@RequestParam(required = false) String title) {
        if (StringUtils.isEmpty(title)) {
            return boardRepository.findAll();
        } else {
            return boardRepository.findByTitle(title);
        }
    }


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

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

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

 

 

제목을 파라미터로 받아서 호출하는 코드 작성

    @GetMapping("/boards")
    List<Board> findByTitle(@RequestParam(required = false) String title) {
        if (StringUtils.isEmpty(title)) {
            return boardRepository.findAll();
        } else {
            return boardRepository.findByTitle(title);
        }
    }

 

BoardRespository.java

package com.toy.board.reopsitory;

import com.toy.board.domain.Board;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface BoardRepository extends JpaRepository<Board, Long> {

    List<Board> findByTitle(String title);
}

BoardRespository 에 findByTitle 생성

 

 

제목과 내용 두 개의 조건 검색 기능 만들기

 

BoardRepository.java

package com.toy.board.reopsitory;

import com.toy.board.domain.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);
}

Spring DATA 의  Namespace 를 이용한다.

 

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

@RequestParam 추가, defaultValue 를 설정

 

 

Postman으로 확인

 

Put도 테스트

 

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

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

 

 

delete 테스트

 

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

'JPA' 카테고리의 다른 글

JPA - Spring Security를 이용한 로그인 처리  (0) 2022.09.10
JPA - Jpa를 이용한 페이지 처리 및 검색  (0) 2022.09.09
JPA - Pageable  (0) 2022.09.02
JPA - Paging  (0) 2022.09.01
JPQL - 벌크 연산  (0) 2022.07.10
복사했습니다!