μ¬μ€ λ΄κ° κ³Όμ λ₯Ό ν λλ κ°μλ₯Ό λ³΄κ³ λ³΅λΆνκ±°λ λ€λ₯Έ μ¬λνν λ§μ΄ λμμ λ°μμ ν΄κ²°μ νλ€.
κ·Έλλ CRUDλ κΈ°λ³Έμ μΌλ‘ μμμΌνμ§ μλκ°....?
μ΄λ° κ°λ¨ν CRUD μ λλ ꡬνν μ μκ² κ³΅λΆλ₯Ό μ΄μ§ νλ€!
γ
: ν΄λΌμ΄μΈνΈμ μμ²μ λ°λλ€.
: μμ²μ λν λ‘μ§ μ²λ¦¬λ Service μκ² μ λ¬νλ€. (Request κ° μλ€λ©΄ κ°μ΄ Service μκ² λ³΄λΈλ€)
: Service μμ μ²λ¦¬ μλ£λ κ²°κ³Όλ₯Ό ν΄λΌμ΄μΈνΈμκ² μλ΅νλ€.
// Controller -> κ°λ¨νκ²
import com.example.post.dto.DeleteResponseDto;
import com.example.post.dto.PostRequestDto;
import com.example.post.dto.PostResponseDto;
import com.example.post.service.PostService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class PostController {
private final PostService postService;
@GetMapping("/post")
public List<PostResponseDto> getPosts () {
return postService.getPosts();
}
@PostMapping("/post")
public PostResponseDto createPost(@RequestBody PostRequestDto postRequestDto) {
return postService.createPost(postRequestDto);
}
@PutMapping("/post/{id}")
public PostResponseDto updatePost(@PathVariable Long id, @RequestBody PostRequestDto postRequestDto) {
return postService.updatePost(id, postRequestDto);
}
@DeleteMapping("/post/{id}")
public DeleteResponseDto deletePost(@PathVariable Long id) {
return postService.deletePost(id);
}
}
: μ¬μ©μ μꡬμ¬νμ μ²λ¦¬νλ μ€μΈ!
: DB μ μ₯ λ° μ‘°νκ° νμν λλ Repositoryμκ² μμ²νλ€.
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
public List<PostResponseDto> getPosts () {
return postRepository.findAllByOrderByCreatedAtDesc()
.stream().map(PostResponseDto::new).toList();
}
public PostResponseDto createPost (PostRequestDto postRequestDto) {
Post post = new Post(postRequestDto);
postRepository.save(post);
return new PostResponseDto(post);
}
@Transactional
public PostResponseDto updatePost(Long id, PostRequestDto postRequestDto) {
Post post = findPost(id);
post.update(postRequestDto);
return new PostResponseDto(post);
}
public DeleteResponseDto deletePost(Long id) {
Post post = findPost(id);
postRepository.delete(post);
return new DeleteResponseDto();
}
public Post findPost (Long id) {
return postRepository.findById(id).orElseThrow(()
-> new IllegalArgumentException("μ νν κ²μκΈμ μ‘΄μ¬νμ§ μμ΅λλ€."));
}
}
: DB κ΄λ¦¬ (μ°κ²°, ν΄μ , μμ κ΄λ¦¬)
: DB CRUD μμ
μ μ²λ¦¬
public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findAllByOrderByCreatedAtDesc();
}