본문 바로가기
Programming/SpringBoot

[Spring Boot] RESTful Service 강의 정리 (16) - JPA를 이용한 개별 사용자 목록 조회 GET HTTP Method

by prinha 2020. 8. 27.
반응형

 

 

[Spring Boot] RESTful Service 강의 정리 (15) - JPA Service 구현을 위한 Controller, Repository 생성

[Spring Boot] RESTful Service 강의 정리 (14) - Spring Data JPA를 이용한 Entity 설정과 초기 데이터 생성 [Spring Boot] RESTful Service 강의 정리 (13) - JPA 사용을 위한 Dependency, h2 DataBase 추가와..

prinha.tistory.com


 

primary key 값을 이용해서 검색 -> findAllById

 

package com.example.restfulwebservice.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("/jpa")
public class UserJpaController {

    @Autowired
    private UserRepository userRepository;

    // 전체 사용자 목록을 조회하는 findAll 메소드 사용
    @GetMapping("/users")
    public List<User> retrieveAllUsers(){
        return userRepository.findAll();
    }

    // 개별 사용자 목록 조회 (가변 데이터 id)
    @GetMapping("/users/{id}")
    public Resource<User> retrieveUser(@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));
        }

        // HATEOAS 기능
        Resource<User> resource = new Resource<>(user.get());
        ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());
        resource.add(linkTo.withRel("all-users"));

        // return user.get();
        return resource;
    }
}

  

 

 

반응형