1일1이론 공부하고, 베이직 강의 영상으로 이론 추가 공부하면서 실습 시도해보기
❓생명주기 관리? → 라스트오더 비유 기억하기
➡️ 컨트롤러에서 먼저 막아야 뒤에서 작업이나 후처리를 마저 하고 종료를 해도 데이터 정합성 (데이터가 올바르고, 일관되며, 깨지지 않도록 유지되는 상태) 을 유지할 수 있다.
살릴 때는 repository → service → controller 순서로
죽일 때는 controller → service → repository 순서로
package com.study.study6.controller;
import com.study.study6.entity.User1;
import com.study.study6.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
// 모든 사용자 조회 - GET
@GetMapping
public ResponseEntity<List<User1>> getAllUsers() {
List<User1> users = userService.findAll();
return new ResponseEntity<>(users, HttpStatus.OK);
}
// ID로 사용자 조회 - GET
@GetMapping("/{id}")
public ResponseEntity<User1> getUserById(@PathVariable Long id) {
Optional<User1> user = userService.findById(id);
if (user.isPresent()) {
return new ResponseEntity<>(user.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
// 사용자 생성 - POST
public ResponseEntity<User1> createUser(@RequestBody User1 user) {
User1 savedUser = userService.save(user);
return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
}
// 사용자 정보 업데이트 - PUT
@PutMapping("/{id}")
public ResponseEntity<User1> updateUser(@PathVariable Long id, @RequestBody User1 user) {
Optional<User1> existingUser = userService.findById(id);
if (existingUser.isPresent()) {
// user.setId(id);
User1 updatedUser = userService.save(user);
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
// ID로 사용자 삭제 - DELETE
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
Optional<User1> user = userService.findById(id);
if (user.isPresent()) {
userService.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}