Spring과 Mysql을 이용해 게시판을 만든다.
Updated:
Database
먼저 Mysql에 테이블을 만들어 준다.
CREATE TABLE Post(
num bigint auto_increment,
id VARCHAR(20),
title VARCHAR(20),
content VARCHAR(1000),
constraint Community_PK PRIMARY KEY(num)
);
이제 이를 이용하기 위해 Spring 프로젝트에 이를 설계해준다.
package com.Member.aiml_server_2024.community;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long num;
private String id;
private String title;
private String content;
}
데이터베이스 접근은 JpaRepository를 사용해 아주 간편하게 사용할 수 있다. JPA는 객체 매핑(ORM, Object-Relational Mapping)을 위한 표준 인터페이스로, SQL을 자동으로 생성해주어, 객체로 데이터에 접근한다.
package com.Member.aiml_server_2024.community;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PostRepository extends JpaRepository<Post, String> {
}
Service & Controller
PostService.java는 다음과 같다.
package com.Member.aiml_server_2024.community;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class PostService {
@Autowired
private PostRepository postRepository;
public List<Post> getAllPosts() {
return postRepository.findAll();
}
public Optional<Post> getPostById(Long num) {
return postRepository.findById(num);
}
public Post creatPost(Post post) {
return postRepository.save(post);
}
public Post updatePost(Long num, Post updatePost) {
Optional<Post> optionalPost = postRepository.findById(num);
if (optionalPost.isPresent()) {
Post existingPost = optionalPost.get();
existingPost.setTitle(updatePost.getTitle());
existingPost.setContent(updatePost.getContent());
return postRepository.save(existingPost);
} else {
throw new IllegalArgumentException("해당 번호의 게시글이 존재하지 않습니다.");
}
}
public void deletePost(Long num) {
postRepository.deleteById(num);
}
}
package com.Member.aiml_server_2024.controller;
import com.Member.aiml_server_2024.community.Post;
import com.Member.aiml_server_2024.community.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/post")
public class PostController {
@Autowired
private PostService postService;
@GetMapping("/")
public List<Post> getAllPost() {
return postService.getAllPosts();
}
@GetMapping("/{num}")
public Optional<Post> getPostById(@PathVariable Long num) {
return postService.getPostById(num);
}
@PostMapping("/")
public Post createPost(@RequestBody Post post) {
return postService.creatPost(post);
}
@PutMapping("/{num}")
public Post updatePost(@PathVariable Long num, @RequestBody Post updatePost) {
return postService.updatePost(num, updatePost);
}
@DeleteMapping("/{num}")
public void deletePost(@PathVariable Long num) {
postService.deletePost(num);
}
}
이를 postman으로 호출하면 잘 동작되는 것을 확인할 수 있다.
댓글남기기