TIL

항해99_TIL220524 (Spring 게시판 만들기)

Hyeongjun_Ham 2022. 5. 25. 00:39

어제부터 해서 프론트단 만들려고 시도했는데 총 18시간쓰고도 실패했다.

스프링 공부를 안해서 불안했는데 기술매니저님이 백엔드부분만 만들어도 배포가 된다고 해서 바로 백엔드만 만들었다.

결국 1시간만에 완성..

 

오늘은 작동 잘 되고 버그나 오류 없었는데, 잘 만든건가 내일 다시 작동하고 개선해야지

 

- PostController

@RestController
@RequiredArgsConstructor
public class PostController {
    private final PostRepository postRepository;
    private final PostService postService;

    //등록
    @PostMapping("/api/posts")
    public Post createPost(@RequestBody PostRequestDto requestDto) {
        Post post = new Post(requestDto);
        return postRepository.save(post);
    }

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

    //게시글 조회
    @GetMapping("/api/posts/{id}")
    public PostDetailDto searchById(@PathVariable Long id) {
        return postService.searchById(id);
    }

    //게시글 삭제
    @DeleteMapping("/api/posts/{id}")
    public boolean deletePost(@PathVariable Long id, @RequestBody PostRequestDto requestDto) {
        if (requestDto.getPassword().equals(postService.check(id))) {
            postRepository.deleteById(id);
            return true;
        } else {
            System.out.println("비밀번호를 확인해 주세요");
            return false;
        }
    }

    //게시글 수정
    @PutMapping("/api/posts/{id}")
    public boolean updatePost(@PathVariable Long id, @RequestBody PostRequestDto requestDto) {
        if (requestDto.getPassword().equals(postService.check(id))) {
            postService.update(id, requestDto);
            return true;
        } else {
            System.out.println("비밀번호를 확인해 주세요");
            return false;
        }
    }
}

게시글 조회, 업데이트, 비밀번호 확인을 Service에서 조작했다.

 

- PostService

@Service
@RequiredArgsConstructor
public class PostService {
    private final PostRepository postRepository;

    //업데이트
    @Transactional
    public Long update(Long id, PostRequestDto requestDto) {
        Post post = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("아이디가 없습니다.")
        );
        post.update(requestDto);
        return id;
    }

    //전체 게시글 조회
    @Transactional()
    public List<PostListDto> searchAllDesc() {
        return postRepository.findAllByOrderByModifiedAtDesc().stream()
                .map(PostListDto::new)
                .collect(Collectors.toList());
    }

    //게시글 조회
    @Transactional
    public PostDetailDto searchById(Long id) {
        Post post = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("아이디가 없습니다.")
        );
        return new PostDetailDto(post);
    }
    //비밀번호 확인
    @Transactional
    public String check(Long id) {
         Post post = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("아이디가 없습니다.")
        );
        return post.getPassword();
    }
}

 

 

전체 게시글 조회, 게시글 조회, Repository에 저장되는 데이터가 다 달라서 Dto를 세개로 나눠서 만들었다.

너무 길어지니 Dto는 생략..

 

1. @RestController

스프링프레임워크 4.x 버전 이상부터 사용가능한 어노테이션으로 @Controller에 @ResponseBody가 결합된 어노테이션이다. 컨트롤러 클래스에 @RestController를 붙이면, 컨트롤러 클래스 하위 메서드에 @ResponseBody 어노테이션을 붙이지 않아도 문자열과 JSON 등을 전송할 수 있습니다.

 

2. @Transactional

데이터베이스 트랜잭션은 데이터베이스 관리 시스템 또는 유사한 시스템에서 상호작용의 단위이다.

여기서 단위라는 말을 사용했는데, 쉽게 말하면 더 이상 쪼개질 수 없는 최소의 연산이라는 의미가 된다.

트랜젝션 메소드가 실행되면

  • 연산이 고립되어, 다른 연산과의 혼선으로 인해 잘못된 값을 가져오는 경우가 방지된다.
  • 연산의 원자성이 보장되어, 연산이 도중에 실패할 경우 변경사항이 Commit되지 않는다.

위의 속성이 보장되기 때문에, 해당 메서드를 실행하는 도중 메서드 값을 수정/삭제하려는 시도가 들어와도 값의 신뢰성이 보장된다. 또한, 연산 도중 오류가 발생해도 rollback해서 DB에 해당 결과가 반영되지 않도록 할 수 있다. 

 

3.

@NoArgsConstructor 어노테이션은 파라미터가 없는 기본 생성자를 생성한다.

@AllArgsConstructor 어노테이션은 모든 필드 값을 파라미터로 받는 생성자를 만들어준다.

@RequiredArgsConstructor 어노테이션은 final이나 @NonNull인 필드 값만 파라미터로 받는 생성자를 만들어준다.

 

- 내일 할 일

- 스프링 강의를 듣고 개념을 좀 더 익히자

- 과제에 오류있나 확인 후 배포까지 끝내자

- 과제 주어진 질문에 대답해보기