feignClient뿐만아니라 그냥mvc패턴 쓰는데 좀헷갈렸던것이 리턴타입을 어떻게 해줘야할지 헷갈렸다.
그래서 한번 알아보았다.
ex) SELECT * FROM users WHERE id = #{id}
흐름
1. mapper에서 user객체 반환
2. serviceImpl에서 user 처리후 반환
3. Controller에서ResponseEntity<user>로 응답
Controller
@GetMapping("/users/{id}") public ResponseEntity<User> getUserById(@PathVariable Long id) { User user = userService.getUserById(id); if (user == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } return ResponseEntity.ok(user); }
리턴타입
성공 시: ResponseEntity<User> (200 OK)
실패 시: ResponseEntity.status(HttpStatus.NOT_FOUND).body(null)(404 Not Found)
ex) SELECT * FROM users
흐름
1. Mapper에서List<User>반환
2. ServiceImpl에서 리스트 처리 후 반환
3. Controller에서ResponseEntity<List<User>>로 응답
Controller
@GetMapping("/users") public ResponseEntity<List<User>> getAllUsers() { List<User> users = userService.getAllUsers(); if (users.isEmpty()) { return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } return ResponseEntity.ok(users); }
리턴타입
성공 시: ResponseEntity<List<User>> (200 OK)
데이터 없음: ResponseEntity.status(HttpStatus.NO_CONTENT).build() (204 No Content)
ex) INSERT INTO users (name, email) VALUES (#{name}, #{email})
흐름
1. Mapper에서 int 반환 (삽입된 행 개수)
2. ServiceImpl에서 삽입 성공 여부 확인 후 반환
3. Controller에서 생성된 User 객체와 함께 응답
Controller
@PostMapping("/users") public ResponseEntity<User> createUser(@RequestBody User user) { int result = userService.createUser(user); if (result > 0) { return ResponseEntity.status(HttpStatus.CREATED).body(user); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
리턴 타입
성공 시: ResponseEntity<User> (201 Created)
실패 시: ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build() (500 Internal Server Error)
ex) UPDATE users SET email = #{email} WHERE id = #{id}
흐름
1. Mapper에서 int 반환 (업데이트된 행 개수)
2. ServiceImpl에서 결과 확인 후 반환
3. Controller에서 응답 코드 설정
Controller
@PutMapping("/users/{id}") public ResponseEntity<Void> updateUser(@PathVariable Long id, @RequestBody User user) { int result = userService.updateUser(id, user); if (result > 0) { return ResponseEntity.ok().build(); } return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); }
리턴타입
성공 시: ResponseEntity.ok().build() (200 OK)
실패 시: ResponseEntity.status(HttpStatus.NOT_FOUND).build() (404 Not Found)
ex) DELETE FROM users WHERE id = #{id}
흐름
1. Mapper에서 int 반환 (삭제된 행 개수)
2. ServiceImpl에서 결과 확인 후 반환
3. Controller에서 응답 코드 설정
Controller
@DeleteMapping("/users/{id}") public ResponseEntity<Void> deleteUser(@PathVariable Long id) { int result = userService.deleteUser(id); if (result > 0) { return ResponseEntity.noContent().build(); } return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); }
리턴 타입
성공 시: ResponseEntity.noContent().build() (204 No Content)
실패 시: ResponseEntity.status(HttpStatus.NOT_FOUND).build() (404 Not Found)