Web/SpringBoot

[SpringBoot/AWS EC2] MongoDB - 4 Delete, selectAll

hjkongkong 2021. 12. 12. 23:07

https://hjkongkong.tistory.com/13

 

[SpringBoot/AWS EC2] MongoDB - 3 Update

https://hjkongkong.tistory.com/12 [SpringBoot/AWS EC2] MongoDB - 2 등록 https://hjkongkong.tistory.com/11 [SpringBoot/AWS EC2] MongoDB - 1 (Auto-Generated Field) 본격적으로 개발을 앞서 오늘 사용 할..

hjkongkong.tistory.com

delete와 Posts를 모두 가져오는 API 만들기

@Transactional
public Long delete(Long id) {
    Posts posts = postsRepository.findById(id)
            .orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
    postsRepository.delete(posts);
    return id;
}

PostsService.java에 delete 관련 코드 추가

 

@DeleteMapping("/api/v1/posts/{id}")
public Long Delete(@PathVariable Long id){
    return postsService.delete(id);
}

PostsApiController.java에 delete에서 사용할 API 추가

 

@Test
public void Posts_삭제(){
    //given
    Posts savedPosts = postsRepository.save(Posts.builder()
            .title("title_delete")
            .content("content_delete")
            .author("author_delete")
            .build());

    Long deleteId = savedPosts.getId();
    String url = "http://localhost:"+port+"/api/v1/posts/"+deleteId;

    //when
    ResponseEntity<Long> responseEntity = restTemplate
            .exchange(url, HttpMethod.DELETE, null,Long.class);

    //then
    assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);

}

delete 관련 test 코드

 


list를 모두 가져오는 코드 작성

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.example.springboot.web.dto;
 
import com.example.springboot.domain.posts.Posts;
import lombok.Getter;
 
@Getter
public class PostsListResponseDto {
    private Long id;
    private String title;
    private String content;
    private String author;
 
    public PostsListResponseDto(Posts document){
        this.id = document.getId();
        this.title = document.getTitle();
        this.content = document.getContent();
        this.author = document.getAuthor();
    }
 
 
}
 
cs

PostsListResponseDto.java

@Transactional(readOnly = true)
public List<PostsListResponseDto> findAll() {

    return postsRepository.findAll().stream()
            .map(PostsListResponseDto::new)
            .collect(Collectors.toList());
}

PostsService.java에 findAll 코드 작성

 

@GetMapping("/api/v1/posts")
public List<PostsListResponseDto> findAll() {
    return postsService.findAll();
}

PostsApiController.java에 Get으로 API 작성

GetMapping이기때문에, Test  코드를 작성하지 않고 웹상에서 확인 가능.

실제 데이터베이스

 

결과 확인