Intro
- Gradle
- Intelli J Community
- Mysql
1. Entity
@Entity
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Builder
@AllArgsConstructor
@Table(name = "boards")
public class BoardEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String content;
public static BoardEntity from(BoardRequestDto requestDto){
return BoardEntity.builder()
.title(requestDto.getTitle())
.content(requestDto.getContent())
.build();
}
public void update(String title, String content){
this.title = title;
this.content = content;
}
}
제목과 내용만 만들었다. DTO를 사용하여 데이터를 가져올 것이기 때문에 DTO에서 Entity를 생성하는 from을 사용했다.
title과 content는 값을 새로 받아와서 변경사항을 업데이트할 때 사용되므로 update 메서드를 따로 생성해주었다.
※ from : DTO 객체에서 필요한 데이터를 받아와서 Entity 객체로 변환하는 작업을 캡슐화할 수 있음, 코드가 더 깔끔하고 직관적.
2. DTO
@Getter
@Setter
public class BoardRequestDto {
private String title;
private String content;
}
요청값을 받아올 DTO 클래스를 만들어주었다.
3. Repository
@Repository
public interface BoardRepository extends JpaRepository<BoardEntity, Long> {
}
4. Service
@Service
@RequiredArgsConstructor
public class BoardService {
private final BoardRepository boardRepository;
//Create : 게시글 저장
public BoardEntity saveBoard(BoardRequestDto requestDto){
return boardRepository.save(BoardEntity.from(requestDto));
}
//Read : 특정 게시글 조회
public BoardEntity getBoard(Long id){
return boardRepository.findById(id)
.orElseThrow(()-> new RuntimeException("해당하는 게시글이 없습니다."));
}
//Read : 모든 게시글 조회
public List<BoardEntity> getAllBoards(){
return boardRepository.findAll();
}
//Update : 특정 게시글 수정
public BoardEntity updateBoard(BoardRequestDto requestDto, Long id){
BoardEntity board = getBoard(id);
board.update(
requestDto.getTitle(),
requestDto.getContent()
);
return boardRepository.save(board);
}
//Delete : 특정 게시글 삭제
public boolean deleteBoard(Long id){
boardRepository.deleteById(id);
return false;
}
}
CRUD 기능이 들어간 서비스 클래스다. getBoard와 updateBoard에서는 id 값을 받아와 해당하는 게시글을 조회 또는 업데이트 하도록 했다. deleteBoard 메서드는 boolean으로 설정하여 해당 게시글을 삭제하고 false를 반환한다.
5. Controller
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/boards")
public class BoardApiController {
private final BoardService boardService;
// 게시글 저장
@PostMapping
public ResponseEntity<BoardEntity> saveBoard(@RequestBody BoardRequestDto requestDto){
BoardEntity savedBoard = boardService.saveBoard(requestDto);
return ResponseEntity.status(201).body(savedBoard);
}
// 특정 게시글 조회
@GetMapping("/{id}")
public ResponseEntity<BoardEntity> getBoard(@PathVariable Long id){
BoardEntity board = boardService.getBoard(id);
if (board == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity
.status(HttpStatus.OK)
.body(board);
}
// 모든 게시글 조회
@GetMapping
public ResponseEntity<List<BoardEntity>> getAllBoards(){
List<BoardEntity> boards = boardService.getAllBoards();
return ResponseEntity.ok(boards);
}
// 특정 게시글 수정
@PutMapping("/{id}")
public ResponseEntity<BoardEntity> updateBoard(@RequestBody BoardRequestDto requestDto, @PathVariable Long id){
BoardEntity updatedBoard = boardService.updateBoard(requestDto, id);
if (updatedBoard == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity
.status(HttpStatus.OK)
.body(updatedBoard);
}
// 특정 게시글 삭제
@DeleteMapping("/{id}")
public ResponseEntity<BoardEntity> deleteBoard(@PathVariable Long id){
boolean isDeleted = boardService.deleteBoard(id);
return isDeleted ? ResponseEntity.notFound().build() : ResponseEntity.noContent().build();
}
}
@RequestMapping을 통해 기본 경로는 /api/boards로 설정했다. @RequestBody를 사용해 DTO의 title과 content 값은 body에서 불러오고, @PathVariable을 사용해 id는 경로에서 값을 가져온다. 서비스 클래스의 deleteBoard 메서드에서 반환한 false 값으로 삭제되지 않았으면 Not Found를, 성공적으로 삭제했을 시 No Content를 반환하도록 했다.
6. Postman
// POST : 게시글 저장하기

// GET : 특정 게시글 조회하기

// GET : 모든 게시글 조회하기

// PUT : 특정 게시글 수정하기

// DELETE : 특정 게시글 삭제하기



감사합니다 ...( _ _)
'Development > Back-end' 카테고리의 다른 글
| [Express] 알리고 API 를 이용한 문자 서비스 예제 (0) | 2025.05.19 |
|---|---|
| [Express] 게시글 관리 미들웨어 (express-validator) (0) | 2025.05.07 |
| [Express] 유저 인증 미들웨어 (0) | 2025.05.07 |
| [Back-end] JWT(JSON Web Token) (0) | 2025.03.14 |
| [Back-end] 서블릿과 JSP (0) | 2025.02.24 |