-
[RESTFUL 학습] JPA를 이용한 CRUD 기본 예제 (RESTCONTROLLER)SPRING/WEBSERVICE 2020. 9. 6. 17:12
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User,Integer> { }
Repository 인터페이스의 메서드를 이용하여 Entity를 참조하거나 수정/추가 할 수 있다.
RESTCONTROLLER 에서는 아래와 같이 CRUD를 사용하면 된다.
@RestController @RequestMapping("/jpa") public class UserJpaController { @Autowired private UserRepository userRepository; // http://localhost:8088/jpa/users // 전체 데이터 Return (READ) @GetMapping("/users") public List<User> retrieveAllUsers() { return userRepository.findAll(); } //해당 ID 데이터 Return (READ) @GetMapping("users/{id}") public EntityModel<User> retrieveUsers(@PathVariable int id) { Optional<User> user = userRepository.findById(id); if(!user.isPresent()) { throw new UserNotFoundException(String.format("ID[%s] not found",id)); } //HATEOAS EntityModel<User> model = new EntityModel<>(user.get()); WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers()); model.add(linkTo.withRel("all-users")); return model; } // Data 삭제 (DELETE) @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id) { userRepository.deleteById(id); } // 데이터 추가 (CREATE) @PostMapping("/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user) { User savedUser = userRepository.save(user); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getId()) .toUri(); return ResponseEntity.created(location).build(); } }
POSTMAN 호출 결과
데이터 추가 데이터 추가 후 데이터 리턴 'SPRING > WEBSERVICE' 카테고리의 다른 글
[RESTFUL 학습] JPA를 이용한 CRUD 심화(유저 -게시물 연동) (1) 2020.10.04 [RESTFUL 학습] JPA를 사용하기 위한 기본 세팅(H2 DB 사용) (0) 2020.09.05 [RESTFUL 학습] spring-security 기본 (0) 2020.08.31 [RESTFUL] HAL BROWSER (0) 2020.08.31 [RESTFUL 학습] SWAGGER 심화-1 (0) 2020.08.31