sm 기술 블로그

[스프링부트] CRUD 본문

스프링부트

[스프링부트] CRUD

sm_hope 2022. 7. 9. 19:55

깃허브 : https://github.com/denist2322/SBstudy

 

GitHub - denist2322/SBstudy

Contribute to denist2322/SBstudy development by creating an account on GitHub.

github.com

CRUD

기본적으로 무엇이 되었든 프로그램(프로젝트)은 생성, 읽기, 수정, 삭제를 기준으로 작성해야 한다.

Ut Class 생성

데이터를 입력받아야 할 때 데이터가 있는지 없는지 체크하기 위해 Utilty를 만들어 줄 것이다.

package com.mysite.sbb.Ut;

public class Ut {
    public static boolean empty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String == false) {
            return true;
        }

        String str = (String) obj;

        return str.trim().length() == 0;
    }
}

DB

먼저 들어가기에 앞서 DB는 다음과 같이 생성할 것이다.

# DB 생성
DROP DATABASE IF EXISTS sbb;
CREATE DATABASE sbb;
USE sbb;

# 회원 테이블 생성
CREATE TABLE `user` (
    id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
    reg_date DATETIME NOT NULL,
    update_date DATETIME NOT NULL,
    email VARCHAR(100) NOT NULL,
    `password` VARCHAR(150) NOT NULL,
    `name` CHAR(50) NOT NULL
);


# 회원 데이터 생성
INSERT INTO `user`
SET reg_date = NOW(),
update_date = NOW(),
email = 'use1@test.com',
`password` = '1234',
`name` = '유저1';

INSERT INTO `user`
SET reg_date = NOW(),
update_date = NOW(),
email = 'use2@test.com',
`password` = '1234',
`name` = '유저2';

INSERT INTO `user`
SET reg_date = NOW(),
update_date = NOW(),
email = 'use3@test.com',
`password` = '1234',
`name` = '유저3';

# 게시물 테이블 생성
CREATE TABLE `article` (
    id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
    reg_date DATETIME NOT NULL,
    update_date DATETIME NOT NULL,
    title VARCHAR(100) NOT NULL,
    `body` TEXT NOT NULL,
    `user_id` BIGINT UNSIGNED NOT NULL
);

# 게시물 데이터 생성
INSERT INTO `article`
SET reg_date = NOW(),
update_date = NOW(),
title = '제목 1',
`body` = '내용 1',
`user_id` = 1;

INSERT INTO `article`
SET reg_date = NOW(),
update_date = NOW(),
title = '제목 2',
`body` = '내용 2',
`user_id` = 2;

INSERT INTO `article`
SET reg_date = NOW(),
update_date = NOW(),
title = '제목 3',
`body` = '내용 3',
`user_id` = 3;

SELECT * FROM article;
SELECT * FROM `user`;

C (Create 생성)

게시물을 생성하는 부분

    @RequestMapping("/doWrite")
    @ResponseBody
    public String doWrite(String title, String body){
        if(Ut.empty(title)){
            return "제목을 입력해주세요.";
        }

        if(Ut.empty(body)){
            return "내용을 입력해주세요.";
        }

        Article article = new Article();
        article.setRegDate(LocalDateTime.now());
        article.setUpdateDate(LocalDateTime.now());
        article.setTitle(title);
        article.setBody(body);
        article.setUserId(1L);

        articleRepository.save(article);

        return "%d번 게시물 생성이 완료되었습니다.".formatted(article.getId());

    }

R (Read 읽기)

게시물을 읽는 부분
1 전체 게시물

    @RequestMapping("/list")
    @ResponseBody
    public List<User> showList(){
        return userRepository.findAll();
    }

2 단일 게시물

    @RequestMapping("/get")
    @ResponseBody
    public Article getArticle(Long id){
        Article article = articleRepository.findById(id).get();

        return article;
    }

U (Update 수정)

게시물을 수정하는 부분

    @RequestMapping("/doModify")
    @ResponseBody
    public String doModify(Long id, String title, String body){
        if(id == null){
            return "id를 입력하세요.";
        }

        if(Ut.empty(title)){
            return "title을 입력하세요.";
        }

        if(Ut.empty(body)) {
            return "body를 입력하세요.";
        }

        Article article = articleRepository.findById(id).get();

        article.setTitle(title);
        article.setBody(body);

        articleRepository.save(article);

        return String.format("%d번 수정이 완료되었습니다.",id);
    }

D (Delete 삭제)

게시물을 삭제하는 부분

    @RequestMapping("/doDelete")
    @ResponseBody
    public String doDelete(Long id){
        if(!articleRepository.existsById(id)){
            return "%d번 게시물은 이미 삭제되었거나 존재하지 않습니다.".formatted(id);
        }

        Article article = articleRepository.findById(id).get();

        articleRepository.delete(article);

        return String.format("%d번 삭제가 완료되었습니다.",id);
    }
Comments