Spring API 만들기
👉 Controller
더보기
package com.sparta.hhblog.controller;
import com.sparta.hhblog.dto.PostCreateDto;
import com.sparta.hhblog.dto.PostEditDto;
import com.sparta.hhblog.dto.PostListDto;
import com.sparta.hhblog.dto.PostShowDto;
import com.sparta.hhblog.entity.Blog;
import com.sparta.hhblog.service.BlogService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequiredArgsConstructor
public class BlogController {
private final BlogService blogService;
// @PostMapping("/api/blogs")
// public Blog createPost(@RequestBody PostCreateDto postCreateDto){
// return blogService.createPost(postCreateDto);
// }
// RequestBody를 사용해서 postman으로 값을 넘기는게 어렵습니다 ㅠㅠ
@PostMapping("/api/createPost/{username}/{pw}/{subject}/{contents}")
public PostCreateDto createPost(@PathVariable String username, @PathVariable String pw, @PathVariable String subject, @PathVariable String contents){
return blogService.createPost(username,pw,subject,contents);
}
@GetMapping("/api/showPost/{id}")
public PostShowDto showPost(@PathVariable Long id){
return blogService.showPost(id);
}
@GetMapping("/api/showAllPost")
public List<PostListDto> getPosts(){
return blogService.getPosts();
}
@PutMapping("/api/editPost/{id}/{pw}/{subject}/{contents}")
public PostEditDto editPost(@PathVariable Long id, @PathVariable String pw, @PathVariable String subject, @PathVariable String contents){
return blogService.editPost(id, pw, subject, contents);
}
@DeleteMapping("/api/deletePost/{id}/{pw}")
public String deletePost(@PathVariable Long id,@PathVariable String pw){
return blogService.deletePost(id,pw);
}
}
👉 DTO
더보기
package com.sparta.hhblog.dto;
import com.sparta.hhblog.entity.Blog;
public class PostCreateDto {
private String contents;
public PostCreateDto(Blog blog) {
this.contents = blog.getContents();
}
}
package com.sparta.hhblog.dto;
import com.sparta.hhblog.entity.Blog;
import lombok.Getter;
@Getter
public class PostEditDto {
private String username;
private String subject;
private String contents;
public PostEditDto(Blog blog) {
this.username = blog.getUsername();
this.subject = blog.getSubject();
this.contents = blog.getContents();
}
}
package com.sparta.hhblog.dto;
import com.sparta.hhblog.entity.Blog;
import lombok.Getter;
import java.time.LocalDateTime;
import java.util.List;
@Getter
public class PostListDto {
private String username;
private String subject;
private String contents;
private LocalDateTime createdAt;
public PostListDto(Blog blog) {
this.username = blog.getUsername();
this.subject = blog.getSubject();
this.contents = blog.getContents();
this.createdAt = blog.getCreatedAt();
}
}
package com.sparta.hhblog.dto;
import com.sparta.hhblog.entity.Blog;
import lombok.Getter;
import java.time.LocalDateTime;
@Getter
public class PostShowDto {
private String username;
private String subject;
private String contents;
private LocalDateTime createdAt;
public PostShowDto(Blog blog) {
this.username = blog.getUsername();
this.createdAt = blog.getCreatedAt();
this.subject = blog.getSubject();
this.contents = blog.getContents();
}
}
👉 Entity
더보기
package com.sparta.hhblog.entity;
import com.sparta.hhblog.dto.PostCreateDto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Getter
@Entity
@NoArgsConstructor
public class Blog extends Timestamped{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String pw;
@Column(nullable = false)
private String subject;
@Column(nullable = false)
private String contents;
public Blog(String username, String pw, String subject, String contents) {
this.username = username;
this.pw = pw;
this.subject = subject;
this.contents = contents;
}
// public Blog(PostCreateDto postCreateDto) {
// this.username = username;
// this.pw = pw;
// this.subject = subject;
// this.contents = contents;
// }
public void edit(String subject, String contents) {
this.subject = subject;
this.contents = contents;
}
}
package com.sparta.hhblog.entity;
import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class Timestamped {
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime modifiedAt;
}
👉 Repository
더보기
package com.sparta.hhblog.repository;
import com.sparta.hhblog.entity.Blog;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BlogRepository extends JpaRepository<Blog,Long> {
List<Blog> findAllByOrderByModifiedAtDesc();
}
👉 Service
package com.sparta.hhblog.service;
import com.sparta.hhblog.dto.PostCreateDto;
import com.sparta.hhblog.dto.PostEditDto;
import com.sparta.hhblog.dto.PostListDto;
import com.sparta.hhblog.dto.PostShowDto;
import com.sparta.hhblog.entity.Blog;
import com.sparta.hhblog.repository.BlogRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@RequiredArgsConstructor
public class BlogService {
private final BlogRepository blogRepository;
// @Transactional
// public Blog createPost(PostCreateDto postCreateDto) {
// Blog blog = new Blog(postCreateDto);
// blogRepository.save(blog);
//
// return blog;
// }
@Transactional
public PostCreateDto createPost(String username, String pw, String subject, String contents) {
Blog blog = new Blog(username, pw, subject, contents);
blogRepository.save(blog);
PostCreateDto postCreateDto = new PostCreateDto(blog);
return postCreateDto;
}
@Transactional
public PostShowDto showPost(Long id) {
Blog blog = blogRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
);
PostShowDto postShowDto = new PostShowDto(blog);
return postShowDto;
}
@Transactional
public List<PostListDto> getPosts() {
List<Blog> blog = blogRepository.findAll();
List<PostListDto> allPosts = new ArrayList<>();
for (Blog blogs : blog) {
PostListDto postListDTO = new PostListDto(blogs);
allPosts.add(postListDTO);
}
return allPosts;
}
@Transactional
public PostEditDto editPost(Long id, String pw, String subject, String contents) {
Blog blog = blogRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
);
if (blog.getPw().equals(pw)) {
blog.edit(subject, contents);
PostEditDto postEditDto = new PostEditDto(blog);
return postEditDto;
} else {
throw new IllegalArgumentException("비밀번호가 일치하지 않습니다");
}
}
@Transactional
public String deletePost(Long id, String pw) {
Blog blog = blogRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
);
if (blog.getPw().equals(pw)) {
blogRepository.deleteById(id);
return "정상적으로 삭제되었습니다.";
}
return "비밀번호가 일치하지 않습니다.";
}
}
🙋♂️ 소감 :
url에는 유의미한 정보만 담겨야 하는데,
나는 모두 PathVariable로 사용해서 url에 모두 노출된다 ㅎㅎ;
RequestBody로 생성과, 수정 부분은 다시 수정해야겠다.
😈 아는 내용이라고 그냥 넘어가지 않기! 😈
'❤️🔥TIL (Today I Learned)' 카테고리의 다른 글
[TIL] 2022-12-13(32day) (0) | 2022.12.14 |
---|---|
[TIL] 2022-12-12(31day) (0) | 2022.12.12 |
[TIL] 2022-12-08(29day) (0) | 2022.12.08 |
[TIL] 2022-12-07(28day) (0) | 2022.12.07 |
[TIL] 2022-12-06(27day) (0) | 2022.12.05 |
댓글