blues_log
Published 2023. 6. 16. 21:01
2023-06-16 TIL (Spring 개인 과제) TIL&WIL

과제 설명

과제 목표 : 스프링 부트를 활용하여 블로그 서버 만들기 ( CRUD 구현하기)

 

요구사항

  • 전체 게시글 목록 조회 API
  • 게시글 작성 API
  • 선택한 게시글 조회 API
  • 선택한 게시글 수정 API
  • 선택한 게시글 삭제 API

API 명세서

Method URL Requset Response
GET (전체 조회, R)  /api/blog - {
{
"createdAt": "2022-07-25T12:43:01.226062”,
"modifiedAt": "2022-07-25T12:43:01.226062”,
"id": 1,
"title": "title2",
"content": "content2",
"author": "author2"
}
....
GET (선택 게시글 조회, R) /api/blog/{id} - {
"createdAt": "2022-07-25T12:43:01.226062”,
"modifiedAt": "2022-07-25T12:43:01.226062”,
"id": 1,
"title": "title2",
"content": "content2",
"author": "author2"
}
POST (작성, C) /api/blog {
"title" : "title",
"content" : "content",
"author" : "author",
"password" : "password"
}
{
"createdAt": "2022-07-25T12:43:01.226062”,
"modifiedAt": "2022-07-25T12:43:01.226062”,
"id": 1,
"title": "title2",
"content": "content2",
"author": "author2"
}
PUT (수정, U) /api/blog/{id} {
"title" : "title2",
"content" : "content2",
"author" : "author2",
"password" :"password2"
}
{
"createdAt": "2022-07-25T12:43:01.226062”,
"modifiedAt": "2022-07-25T12:43:01.226062”,
"id": 1,
"title": "title2",
"content": "content2",
"author": "author2"
}
DELETE (삭제, D) /api/blog/{id} {
"password" :"password"
}
{
"success": true
}
       

주요 코드

id와 비밀번호 확인

id와 비밀번호를 동시에 확인하기 위해서 Query Methods를 활용했다.

Repository 클래스에 다음과 같이 작성하면 된다.

Blog findByPasswordAndId(String password, Long id);

그 후 Service 클래스에서 수정과 삭제 기능을 다음과 같이 구현하면 된다.

@Transactional
public Long updateBlog(Long id, BlogRequestDto requestDto) { //수정기능
	// 해당 메모가 DB에 존재하는지 확인
	Blog blog = blogRepository.findByPasswordAndId(requestDto.getPassword(), id);

	// blog 내용 수정
	if(blog != null) {
		blog.update(requestDto);
	} else {
		throw new IllegalArgumentException("해당 게시글이 존재하지 않거나 비밀번호가 틀렸습니다.");
	}
	return id;
}
 public Long deleteBlog(Long id, BlogRequestDto requestDto) { //삭제기능
    Blog blog = blogRepository.findByPasswordAndId(requestDto.getPassword(), id);
    if(blog != null) {
    	// blog 삭제
        blogRepository.delete(blog);
    } else {
        throw new IllegalArgumentException("해당 게시글이 존재하지 않거나 비밀번호가 틀렸습니다.");
    }
    return id;
}

작성 날짜 기준 내림차순 정렬

역시 Query Methods를 활용하면 된다.

List<Blog> findAllByOrderByModifiedAtDesc(); //작성 날짜 기준 내림차순 정렬

전체 코드

다음 링크를 확인!

https://github.com/hakjunjoo/blog-spring-prac

 

GitHub - hakjunjoo/blog-spring-prac

Contribute to hakjunjoo/blog-spring-prac development by creating an account on GitHub.

github.com


느낀점

코드의 대부분은 강의에서 학습한 내용을 그대로 클론해서 작성했다.

우선 코드에 대한 이해를 우선적으로 생각했고, 대략적인 내용은 전부 이해를 하기위해 노력했다.

 

스스로 구현하는 연습을 많이해서 스프링부트에 익숙해지기 위해 노력해야겠다.