본문 바로가기
프레임워크/스프링

[Spring] RestApi 게시판 만들기

by Yikanghee 2022. 5. 4.

React로 게시판을 만들기 위해서 RestApi 형태로 게시판을 만들어 보았다

package com.mobee.movie.controller;

import com.mobee.movie.dto.ModifyPostsDTO;
import com.mobee.movie.dto.PostsResDTO;
import com.mobee.movie.dto.RegistPostsDTO;
import com.mobee.movie.service.PostsService;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping(value = {"/posts"}, produces = MediaType.APPLICATION_JSON_VALUE)
@AllArgsConstructor
public class PostsController {

    private PostsService postsService;

    // 게시글 목록 조회
    @GetMapping({""})
    public ResponseEntity<List<PostsResDTO>> getPosts() {
        return ResponseEntity.ok()
                .body(postsService.getPostsService());
    }

    // 게시글 등록
    @PostMapping({""})
    public ResponseEntity<Long> regPosts(@Valid @RequestBody RegistPostsDTO registPostsDTO) {
        return ResponseEntity.ok()
                .body(postsService.regPostsService(registPostsDTO));
    }

    // 게시글 상세 조회
    @GetMapping("/{id}")
    public ResponseEntity<PostsResDTO> getPostsDetail(@PathVariable Long id) throws Exception {
        return ResponseEntity.ok()
                .body(postsService.getPostsByIdService(id));
    }

    // 게시글 수정
    @PutMapping("/{id}")
    public ResponseEntity<String> ModifyPosts(
            @PathVariable Long id,
            @Valid @RequestBody ModifyPostsDTO modifyPostsDTO) {

        postsService.setPostsService(modifyPostsDTO);

        return ResponseEntity.ok()
                .body("UPDATE SUCCESS");
    }

    // 게시글 삭제
    @DeleteMapping("/{id}")
    public ResponseEntity<String> delPosts(
            @PathVariable Long id) {
        postsService.delPostsService(id);

        return ResponseEntity.ok()
                .body("DELETE SUCCESS");
    }

}

컨트롤러

 

package com.mobee.movie.service;

import com.mobee.movie.dto.ModifyPostsDTO;
import com.mobee.movie.dto.PostsResDTO;
import com.mobee.movie.dto.RegistPostsDTO;
import com.mobee.movie.entity.Posts;
import com.mobee.movie.repository.PostsRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("postService")
@AllArgsConstructor
public class PostsService {

    private PostsRepository postsRepository;

    // 글 목록 조회
    public List<PostsResDTO> getPostsService() {

        List<Posts> entityList = postsRepository.findAll();
        List<PostsResDTO> result = new ArrayList<>();

        entityList.forEach(entity -> {
            PostsResDTO rDTO = new PostsResDTO();
            rDTO.setId(entity.getId());
            rDTO.setAuthor(entity.getAuthor());
            rDTO.setTitle(entity.getTitle());
            rDTO.setContent(entity.getContent());
            rDTO.setCreatedDate(entity.getCreatedDate());
            rDTO.setModifiedDate(entity.getModifiedDate());
            result.add(rDTO);
        });

        return result;
    }

    // 글 등록
    public Long regPostsService(RegistPostsDTO regPosts) {
        Long insertId = postsRepository.save(regPosts.toEntity()).getId();

        return insertId;
    }

    // 글 상세 조회
    public PostsResDTO getPostsByIdService(Long id) throws Exception {

        Posts entity = postsRepository.findById(id)
                .orElseThrow(() -> new Exception("해당 게시글이 없습니다"));

        PostsResDTO rDTO = new PostsResDTO();
        rDTO.setId(entity.getId());
        rDTO.setAuthor(entity.getAuthor());
        rDTO.setTitle(entity.getTitle());
        rDTO.setContent(entity.getContent());
        rDTO.setCreatedDate(entity.getCreatedDate());
        rDTO.setModifiedDate(entity.getModifiedDate());

        return rDTO;
    }

    // 글 수정
    public void setPostsService(ModifyPostsDTO setPosts) {
        postsRepository.save(setPosts.toEntity());
    }

    // 글 삭제
    public void delPostsService(Long id) {
        postsRepository.deleteById(id);
    }







}

서비스

 

package com.mobee.movie.entity;

import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.time.LocalDateTime;

@Getter
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EntityListeners(AuditingEntityListener.class)
public class Posts {

    @Id
    @GeneratedValue
    private Long id;

    @Column(length = 10, nullable = false)
    private String author;

    @Column(length = 100, nullable = false)
    private String title;

    @Column(columnDefinition = "TEXT", nullable = false)
    private String content;

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdDate;

    @LastModifiedDate
    private LocalDateTime modifiedDate;

    @Builder
    public Posts(Long id, String author, String title, String content) {

        this.id = id;
        this.author = author;
        this.title = title;
        this.content = content;
    }
}

Entity

 

package com.mobee.movie.repository;

import com.mobee.movie.entity.Posts;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface PostsRepository extends JpaRepository<Posts, Long> {

}

Repository

JPA 사용을 위해서 추가해준다

 

package com.mobee.movie.dto;

import com.mobee.movie.entity.Posts;
import lombok.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;

@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class ModifyPostsDTO {

    @Min(1)
    private Long id;

    @NotBlank(message = "필수 사항입니다")
    private String author;

    @NotBlank(message = "필수 사항입니다")
    private String title;

    @NotBlank(message = "필수 사항입니다")
    private String content;

    public Posts toEntity() {
        Posts build = Posts.builder()
                .id(id)
                .author(author)
                .title(title)
                .content(content)
                .build();
        return build;
    }

}

수정 DTO

 

package com.mobee.movie.dto;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

import java.time.LocalDateTime;

@Getter
@Setter
@ToString
@NoArgsConstructor
public class PostsResDTO {

    private Long id;
    private String author;
    private String title;
    private String content;
    private LocalDateTime createdDate;
    private LocalDateTime modifiedDate;
}

조회 DTO

 

 

package com.mobee.movie.dto;

import com.mobee.movie.entity.Posts;
import lombok.*;

import javax.validation.constraints.NotBlank;

@Getter
@Setter
@ToString
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class RegistPostsDTO {

    @NotBlank(message = "필수 항목입니다")
    private String author;

    @NotBlank(message = "필수 항목입니다")
    private String title;

    @NotBlank(message = "필수 항목입니다")
    private String content;

    public Posts toEntity() {

        Posts build = Posts.builder()
                .author(author)
                .title(title)
                .content(content)
                .build();

        return build;
    }
}

등록 DTO

댓글