본문 바로가기
Programming/SpringBoot

[Spring Boot] RESTful Service 강의 정리 (19) - 게시물 조회를 위한 Post Entity와 User Entity의 관계 설정

by prinha 2020. 8. 27.
반응형

 

 

[Spring Boot] RESTful Service 강의 정리 (18) - 게시물 관리를 위한 Post Entity 추가와 초기 데이터 생성

[Spring Boot] RESTful Service 강의 정리 (17) - JPA를 이용한 사용자 추가와 삭제 - POST/DELETE HTTP Method [Spring Boot] RESTful Service 강의 정리 (16) - JPA를 이용한 개별 사용자 목록 조회 GET HTTP Me..

prinha.tistory.com


Post Entity와 User Entity의 게시물 조회

 

 

UserJpaController method 작성

// Post Entity를 사용할 수 있는 게시물 조회 메소드
@GetMapping("/users/{id}/posts")
public List<Post> retrieveAllPostByUser(@PathVariable int id){

    Optional<User> user = userRepository.findById(id);

    // Optional<T> findById(ID var1)
    // 리턴값이 Optional인 이유 : 데이터가 존재할수도 안할수도 있기때문에

    if(!user.isPresent()){
        throw  new UserNotFoundException(String.format("ID[%s] not found",id));
    }

    return user.get().getPosts();
}

 

게시물 조회 완료

 

 

 

 

반응형