본문 바로가기
CRUD 게시판

RestApi 게시판 CRUD 만들기 (2) - Service , Controller

by YoonJong 2022. 10. 12.
728x90

PostService 

@RequiredArgsConstructor
@Service
public class PostService {

    private final PostRepository postRepository;

    //등록
    @Transactional
    public void create(@RequestBody CreatePostDto createPostDto) {
        Post post = Post.builder()
                .title(createPostDto.getTitle())
                .content(createPostDto.getContent())
                .build();

        postRepository.save(post);
    }

    //1건 조회
    @Transactional(readOnly = true)
    public PostsResponse findOne(Long id) {
        Post findPost = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("찾는 게시물이 없습니다. id =" + id));

        PostsResponse response = PostsResponse.builder()
                .id(findPost.getId())
                .title(findPost.getTitle())
                .content(findPost.getContent())
                .build();

        return response;

    }

    // 전체조회
    @Transactional(readOnly = true)
    public List<PostsResponse> findAll() {
        return postRepository.findAll().stream()
                .map(post -> new PostsResponse(post))
                .collect(Collectors.toList());
    }

    // 수정 (제목,내용)
    @Transactional
    public void update(Long id, @RequestBody UpdatePostDto updatePostDto) {
        Post post = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("게시글을 찾을 수 없습니다. id = " + id));

        PostConvert postConvert = post.toConvert();

        postConvert.setTitle(updatePostDto.getTitle());
        postConvert.setContent(updatePostDto.getContent());

        post.update(postConvert);

    }

    // 삭제
    @Transactional
    public void delete(Long id) {
        Post post = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("게시글을 찾을 수 없습니다. id = " + id));

        postRepository.deleteById(post.getId());
    }
}

 

게시글등록

//등록
@Transactional
public void create(@RequestBody CreatePostDto createPostDto) {
    Post post = Post.builder()
            .title(createPostDto.getTitle())
            .content(createPostDto.getContent())
            .build();

    postRepository.save(post);
}
  • JPA 에서는 @Transactional 를 꼭 붙여준다. -> DB 에 변화가 있다.
  • HTTP 요청과 함께 받은 JSON 데이터를 Java 객체에 매핑하기 위해 @RequestBody 를 사용
  • 생성할때 요청받을 CreatePostDto 를 사용
  • postRepository 는 Post 형태만 받을 수 있다. 따라서 Post builder 를 사용해 post 를 생성해준다
    post 의 id 는 자동증가가 되기때문에 따로 설정할 필요 없다.

 

게시글 1건조회

//1건 조회
@Transactional(readOnly = true)
public PostsResponse findOne(Long id) {
    Post findPost = postRepository.findById(id).orElseThrow(
            () -> new IllegalArgumentException("찾는 게시물이 없습니다. id =" + id));

    PostsResponse response = PostsResponse.builder()
            .id(findPost.getId())
            .title(findPost.getTitle())
            .content(findPost.getContent())
            .build();

    return response;
}
  • 조회는 DB에 변화가 없으므로, @Transactional (readOnly = true) 를 붙여주어 성능이 향상되도록 한다.
  • 응답은 PostsResponse 로 받아 Json 형태로 받을 수 있다.
  • 찾는 id 가 없을 수 있기 때문에, orElseThrow 를 사용해 예외를 던져준다.
  • 찾을경우 응답해줄 형태인 PostsResposne builder 를 사용해 해당 형태로 만들어주며 리턴해준다.

 

게시글 전체조회

// 전체조회
@Transactional(readOnly = true)
public List<PostsResponse> findAll() {
    return postRepository.findAll().stream()
            .map(post -> new PostsResponse(post))
            .collect(Collectors.toList());
}
  • 전체조회는 List 로 받아야하며 해당 타입은 PostsResponse 이다.
  • postRepository.findAll() 메서드로 받으면 해당 타입은 Post 타입이므로, 형변환을 해주어야한다.
  • stream 과 map 을 사용해 PostsResponse 형태로 변환한다.

 

게시글 수정(제목,내용)

// 수정 (제목,내용)
@Transactional
public void update(Long id, @RequestBody UpdatePostDto updatePostDto) {
    Post post = postRepository.findById(id).orElseThrow(
            () -> new IllegalArgumentException("게시글을 찾을 수 없습니다. id = " + id));

    PostConvert postConvert = post.toConvert();

    postConvert.setTitle(updatePostDto.getTitle());
    postConvert.setContent(updatePostDto.getContent());

    post.update(postConvert);

}
  • 먼저 게시글을 찾아야 하므로 id 를 받아 확인
  • 값을 변경시켜주기 위해 post 를 postConvert 형태로 변경 -> post에는 setter 가 없다. ( Entity 이기 때문)
  • 받은 updatePostDto 값을 postConvert 형태에서 변경
  • 처음 id 로 찾은 post 값을 update 메소드를 통해 변경

 

게시글 삭제

// 삭제
@Transactional
public void delete(Long id) {
    Post post = postRepository.findById(id).orElseThrow(
            () -> new IllegalArgumentException("게시글을 찾을 수 없습니다. id = " + id));

    postRepository.deleteById(post.getId());
}
  • id 를 통해 삭제할 게시글을 찾는다

PostController


@RequiredArgsConstructor
@RestController
public class PostController {

    private final PostService postService;

    // 게시글 작성
    @PostMapping("/posts")
    public void create(@RequestBody CreatePostDto createPostDto) {
        postService.create(createPostDto);
    }

    // 게시글 전체조회
    @GetMapping("/posts")
    public List<PostsResponse> findAll() {
        return postService.findAll();
    }

    // 게시글 단건조회
    @GetMapping("/posts/{id}")
    public PostsResponse findOne(@PathVariable Long id) {
        return postService.findOne(id);
    }

    // 게시글 수정 ( 제목, 내용 )
    @PatchMapping("/posts/{id}")
    public void update(@PathVariable Long id, @RequestBody UpdatePostDto updatePostDto) {
        postService.update(id, updatePostDto);
    }

    // 게시글 삭제
    @DeleteMapping("/posts/{id}")
    public void delete(@PathVariable Long id) {
        postService.delete(id);
    }
}

 

728x90

댓글