@Entity
@Getter @Setter
@NoArgsConstructor
public class Post {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "post_id")
private Long id;
private String title;
private String content;
public Post(String title, String content) {
this.title = title;
this.content = content;
}
}
PostDto
게시글 작성 시 필요한 DTO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PostDto {
private String title;
private String content;
}
2-3. repository
PostRepository
JpaRepository 상속
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}
2-4. service
PostService
기본적인 게시글 작성, 조회 로직만 포함
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
// 모든 게시글 리턴
public List<Post> findAll() {
return postRepository.findAll();
}
// 특정 게시글 리턴
public Post findById(Long postId) {
return postRepository.findById(postId).orElse(null);
}
// 게시글 저장
@Transactional
public Post save(PostDto postDto) {
Post post = new Post(postDto.getTitle(), postDto.getContent());
return postRepository.save(post);
}
}
2-5. controller
PostApiController
REST API 사용 방식으로 구현
기본적인 게시글 작성, 조회 로직만 포함
@RestController
@RequiredArgsConstructor
@RequestMapping("/v0/api/posts")
public class PostApiController {
private final PostService postService;
// 모든 게시글 조회
@GetMapping
public ResponseEntity<List<Post>> findAllPosts() {
return ResponseEntity.ok(postService.findAll());
}
// 특정 게시글 단건 조회
@GetMapping("/{postId}")
public ResponseEntity<Post> findPost(@PathVariable("postId") Long postId) {
Post post = postService.findById(postId);
return post == null ? ResponseEntity.status(HttpStatus.NO_CONTENT).body(null) : ResponseEntity.ok(post);
}
// 게시글 작성
@PostMapping
public ResponseEntity<Post> savePost(@RequestBody PostDto postDto) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(postService.save(postDto));
}
}
3. 공통 실행 결과
Postman으로 결과 확인
3-1. 게시글 작성 (POST localhost:8080/v0/api/posts)
3-2. 모든 게시글 조회 (GET localhost:8080/v0/api/posts)
3-3. 특정 게시글 조회 (GET localhost:8080/v0/api/posts/1)