diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..81bb237 --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# IntelliJ +.idea/ +*.iml + +# IntelliJ Local Settings +/workspace.xml +/shelf/ +/httpRequests/ +/queries/ +/dataSources/ +/dataSources.local.xml + +# macOS +.DS_Store + +# Gradle +.gradle/ +build/ + +# Environment +.env + +# Logs +*.log + +# Spring Boot +target/ +out/ \ No newline at end of file diff --git a/spring-db/README.md b/spring-db/README.md new file mode 100644 index 0000000..5f56710 --- /dev/null +++ b/spring-db/README.md @@ -0,0 +1,27 @@ +# 과제명 +게시판 + DB 연동 + +## ⚙️ 실행 방법 +1. MySQL에서 데이터베이스 생성 +``` +CREATE DATABASE post_server +``` +2. .env에 DB 정보 입력 +3. IntelliJ에서 RestApiServerApplication.java 실행 + +## 💡 작업 내용 +- 게시글 CRUD 구현 +- MySQL 연동 +- JPA 사용 + +## 📡 API 명세 (Spring 과제의 경우) +| Method | URI | 설명 | +|--------|-------------|-----------| +| POST | /posts | 게시글 생성 | +| GET | /posts | 전체 게시글 조회 | +| GET | /posts/{id} | 단건 게시글 조회 | +| PUT | /posts/{id} | 게시글 수정 | +| DELETE | /posts/{id} | 게시글 삭제 | + +## 🤔 느낀 점 / 어려웠던 점 +- 저번에 비해서 예외 처리 방식에 대해서 살펴본 것 같고 각 어노테이션의 역할에 대해서도 좀 더 알아본 것 같다. \ No newline at end of file diff --git a/spring-db/images/createPost_id_1.png b/spring-db/images/createPost_id_1.png new file mode 100644 index 0000000..931f8db Binary files /dev/null and b/spring-db/images/createPost_id_1.png differ diff --git a/spring-db/images/createPost_id_2.png b/spring-db/images/createPost_id_2.png new file mode 100644 index 0000000..0bc52b6 Binary files /dev/null and b/spring-db/images/createPost_id_2.png differ diff --git a/spring-db/images/deletePost_id_1.png b/spring-db/images/deletePost_id_1.png new file mode 100644 index 0000000..abe88dc Binary files /dev/null and b/spring-db/images/deletePost_id_1.png differ diff --git a/spring-db/images/getAllPosts_1.png b/spring-db/images/getAllPosts_1.png new file mode 100644 index 0000000..bdaa75a Binary files /dev/null and b/spring-db/images/getAllPosts_1.png differ diff --git a/spring-db/images/getAllPosts_2.png b/spring-db/images/getAllPosts_2.png new file mode 100644 index 0000000..24d2230 Binary files /dev/null and b/spring-db/images/getAllPosts_2.png differ diff --git a/spring-db/images/getAllPosts_result_1.png b/spring-db/images/getAllPosts_result_1.png new file mode 100644 index 0000000..718c4f9 Binary files /dev/null and b/spring-db/images/getAllPosts_result_1.png differ diff --git a/spring-db/images/getAllPosts_result_2.png b/spring-db/images/getAllPosts_result_2.png new file mode 100644 index 0000000..c14bb6d Binary files /dev/null and b/spring-db/images/getAllPosts_result_2.png differ diff --git a/spring-db/images/getPostById_id_2.png b/spring-db/images/getPostById_id_2.png new file mode 100644 index 0000000..accf49a Binary files /dev/null and b/spring-db/images/getPostById_id_2.png differ diff --git a/spring-db/images/mysql_1.png b/spring-db/images/mysql_1.png new file mode 100644 index 0000000..8ee7fef Binary files /dev/null and b/spring-db/images/mysql_1.png differ diff --git a/spring-db/images/mysql_2.png b/spring-db/images/mysql_2.png new file mode 100644 index 0000000..f1ee18a Binary files /dev/null and b/spring-db/images/mysql_2.png differ diff --git a/spring-db/images/updatePost_id_2.png b/spring-db/images/updatePost_id_2.png new file mode 100644 index 0000000..6c84ff1 Binary files /dev/null and b/spring-db/images/updatePost_id_2.png differ diff --git a/spring-db/spring-db/HELP.md b/spring-db/spring-db/HELP.md new file mode 100644 index 0000000..4ee7e0a --- /dev/null +++ b/spring-db/spring-db/HELP.md @@ -0,0 +1,24 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Gradle documentation](https://docs.gradle.org) +* [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/4.0.6/gradle-plugin) +* [Create an OCI image](https://docs.spring.io/spring-boot/4.0.6/gradle-plugin/packaging-oci-image.html) +* [Spring Web](https://docs.spring.io/spring-boot/4.0.6/reference/web/servlet.html) +* [Spring Data JPA](https://docs.spring.io/spring-boot/4.0.6/reference/data/sql.html#data.sql.jpa-and-spring-data) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) + +### Additional Links +These additional references should also help you: + +* [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) + diff --git a/spring-db/spring-db/build.gradle b/spring-db/spring-db/build.gradle new file mode 100644 index 0000000..6d9c0fc --- /dev/null +++ b/spring-db/spring-db/build.gradle @@ -0,0 +1,31 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.0.6' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.task' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + runtimeOnly 'com.mysql:mysql-connector-j' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/spring-db/spring-db/gradle/wrapper/gradle-wrapper.jar b/spring-db/spring-db/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc Binary files /dev/null and b/spring-db/spring-db/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spring-db/spring-db/gradle/wrapper/gradle-wrapper.properties b/spring-db/spring-db/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c61a118 --- /dev/null +++ b/spring-db/spring-db/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/spring-db/spring-db/gradlew b/spring-db/spring-db/gradlew new file mode 100755 index 0000000..739907d --- /dev/null +++ b/spring-db/spring-db/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/spring-db/spring-db/gradlew.bat b/spring-db/spring-db/gradlew.bat new file mode 100644 index 0000000..e509b2d --- /dev/null +++ b/spring-db/spring-db/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spring-db/spring-db/settings.gradle b/spring-db/spring-db/settings.gradle new file mode 100644 index 0000000..e304a42 --- /dev/null +++ b/spring-db/spring-db/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'RestAPIServer' diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/RestApiServerApplication.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/RestApiServerApplication.java new file mode 100644 index 0000000..bf80fe2 --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/RestApiServerApplication.java @@ -0,0 +1,19 @@ +package com.task.RestAPIServer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +// JPA Auditing 기능 활성화 +// GlobalEntity의 @CreatedDate, @LastModifiedDate를 사용하기 위함 +@EnableJpaAuditing + +// 이 클래스가 Spring Boot Application의 시작점임을 나타냄 +@SpringBootApplication +public class RestApiServerApplication { + + public static void main(String[] args) { + SpringApplication.run(RestApiServerApplication.class, args); + } + +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/controller/PostController.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/controller/PostController.java new file mode 100644 index 0000000..d910f45 --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/controller/PostController.java @@ -0,0 +1,102 @@ +package com.task.RestAPIServer.controller; + +import com.task.RestAPIServer.dto.PostResponse; +import com.task.RestAPIServer.dto.PostRequest; +import com.task.RestAPIServer.entity.Post; +import com.task.RestAPIServer.service.PostService; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import lombok.RequiredArgsConstructor; + +// final 필드를 대상으로 생성자를 자동 생성 +// postService를 생성자 주입 방식으로 주입바기 위해 사용 +@RequiredArgsConstructor + +// 이 클래스가 REST API Controller임을 나타냄 +// 반환값은 주로 JSON 형태로 응답 +@RestController + +// 이 Controller의 기본 URL 경로를 /posts로 설정 +@RequestMapping("/posts") +public class PostController { + + // 게시글 관련 비즈니스 로직을 처리하는 Service + // final로 선언했기 때문에 @RequiredArgsConstructor를 통해 생성자 주입 + private final PostService postService; + + // 단건 게시글 조회 + // GET /posts/{id} 요청 처리 + @GetMapping("{id}") + public ResponseEntity getPostById(@PathVariable("id") long id) { + + // URL 경로에서 받은 id를 기준으로 게시글 조회, 로직은 Service 계층에서 처리 + Post post = postService.findById(id); + + // 조회한 Post Entity를 PostResponse DTO로 반환하여 HTTP 200 OK 상태 코드와 함께 반환 + return ResponseEntity.ok(new PostResponse(post)); + } + + // 전체 게시글 조회 + // GET /posts 요청 처리 + // Pagable을 통해 페이징 정보를 받음, 예) GET /posts?page=0&size=10 + @GetMapping + public ResponseEntity> getAllPosts(Pageable pageable) { + + // Service에서 페이징 처리된 게시글 목록 조회, 조회 결과는 Page 형태 + // map(PostResponse::new)를 사용하여 각 Post를 PostResponse로 변환 + Page postsResponse = postService.findAllPosts(pageable) + .map(PostResponse::new); + + // 변환된 게시글 목록을 HTTP 200 OK 상태 코드와 함께 반환 + return ResponseEntity.ok(postsResponse); + } + + // 게시글 생성 + // POST /posts 요청 처리 + @PostMapping + public ResponseEntity createPost(@RequestBody PostRequest request) { + + // PostRequest 데이터를 이용하여 게시글 생성, 저장 로직은 Service 계층에서 관리 + Post createdPost = postService.save(request); + + // 생성된 게시글을 PostResponse DTO로 변환하여 반환 + // 게시글 생성에 성공했으면 HTTP 201 CREATED 상태 코드를 사용 + return ResponseEntity + .status(HttpStatus.CREATED) + .body(new PostResponse(createdPost)); + } + + // 게시글 수정 + // PUT /posts/{id} 요청 처리 + @PutMapping("{id}") + public ResponseEntity updatePost( + + // URL 경로에서 수정할 게시글의 id를 가져옴 + @PathVariable("id") long id, + + // 요청 본문에서 수정할 제목, 내용 등의 데이터를 가져옴 + @RequestBody PostRequest postRequest + ) { + + // id에 해당하는 게시글을 postRequest의 내용으로 수정, 수정 로직은 Service 계층에서 관리 + Post updatedPost = postService.update(id, postRequest); + + // 수정된 게시글을 PostResponse DTO로 변환하여 HTTP 200 OK 상태 코드와 함께 반환 + return ResponseEntity.ok(new PostResponse(updatedPost)); + } + + // 게시글 삭제 + // DELETE /posts/{id} 요청 처리 + @DeleteMapping("{id}") + public ResponseEntity deletePost(@PathVariable("id") long id) { + + // id에 해당하는 게시글을 삭제, 삭제 로직은 Service 계층에서 관리 + postService.delete(id); + + // 삭제 성공 시 응답 본문 없이 HTTP 204 No Content 상태 코드 반환 + return ResponseEntity.noContent().build(); + } +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/ErrorResponse.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/ErrorResponse.java new file mode 100644 index 0000000..da56e52 --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/ErrorResponse.java @@ -0,0 +1,20 @@ +package com.task.RestAPIServer.dto; + +import java.time.LocalDateTime; + +// 에러 응답 정보를 담기 위한 DTO +// record는 생성자, getter 역할의 메소드, equals(), toString() 등이 자동 생성 +public record ErrorResponse ( + + // HTTP 상태 코드를 의미 + int status, + + // 에러의 종류 또는 상태 문구를 의미 + String error, + + // 클라이언트에 보여줄 구체적인 에러 메시지 + String message, + + // 에러가 발생한 시간 + LocalDateTime timestamp +) {} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/PostRequest.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/PostRequest.java new file mode 100644 index 0000000..5a65b54 --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/PostRequest.java @@ -0,0 +1,12 @@ +package com.task.RestAPIServer.dto; + +// 게시글 생성 또는 수정 요청 데이터를 담기 위한 DTO +public record PostRequest( + + // 클라이언트가 요청으로 전달하는 게시글 제목 + String title, + + // 클라이언트가 요청으로 전달하는 게시글 내용 + String content +) { +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/PostResponse.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/PostResponse.java new file mode 100644 index 0000000..6d3613e --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/dto/PostResponse.java @@ -0,0 +1,47 @@ +package com.task.RestAPIServer.dto; + +import com.task.RestAPIServer.entity.Post; + +import java.time.LocalDateTime; + +// 게시글 응답 데이터를 담기 위한 DTO로 클라이언트에 게시글 정보를 반환할 때 사용 +public record PostResponse( + + // 게시글의 고유 ID + Long id, + + // 게시글의 제목 + String title, + + // 게시글의 내용 + String content, + + // 게시글이 생성된 시간 + LocalDateTime createdAt, + + // 게시글이 마지막으로 수정된 시간 + LocalDateTime updatedAt +) { + // Post Entity 객체를 PostResponse DTO로 변환하기 위한 생성자 + // Controller에서 new PostResponse(post)처럼 사용할 수 있게 함 + public PostResponse(Post post) { + + // record의 기본 생성자를 호출 + this( + // Post Entity의 id 값을 가져와 PostResponse의 id에 넣음 + post.getId(), + + // Post Entity의 title 값을 가져와 PostResponse의 title에 저장 + post.getTitle(), + + // Post Entity의 content 값을 가져와 PostResponse의 content에 저장 + post.getContent(), + + // Post Entity의 createdAt 값을 가져와 PostResponse의 createdAt에 저장 + post.getCreatedAt(), + + // Post Entity의 updatedAt 값을 가져와 PostResponse의 updatedAt에 저장 + post.getUpdatedAt() + ); + } +} \ No newline at end of file diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/entity/GlobalEntity.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/entity/GlobalEntity.java new file mode 100644 index 0000000..9bec970 --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/entity/GlobalEntity.java @@ -0,0 +1,37 @@ +package com.task.RestAPIServer.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +// Lombok을 통해 이 클래스의 필드에 대한 getter를 자동 생성 +@Getter + +// 이 클래스가 독립적인 Entity가 아닌 다른 Entity들이 공통 필드를 상속받기 위한 부포 클래스임을 의미 +@MappedSuperclass + +// JPA Auditing 기능을 사용하기 위해 AuditingEntityListener를 등록 +// Entity가 저장되거나 수정될 때, createdAt, updatedAt 값을 자동 처리 +@EntityListeners(AuditingEntityListener.class) +public class GlobalEntity { + + // Entity가 처음 생성되어 저장될 때 현재 시간이 자등으로 들어감 + @CreatedDate + + // DB 컬럼 설정으로, null 값을 허용하지 않으며 한 번 저장된 후 수정되지 않음 + @Column(nullable = false, updatable = false) + private LocalDateTime createdAt; + + // Entity가 수정될 때 마다 현재 시간이 자동으로 갱신 + @LastModifiedDate + + // DB 컬럼 설정으로, null 값을 허용하지 않음 + @Column(nullable = false) + private LocalDateTime updatedAt; +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/entity/Post.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/entity/Post.java new file mode 100644 index 0000000..11a48c0 --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/entity/Post.java @@ -0,0 +1,50 @@ +package com.task.RestAPIServer.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + + +// Lombok을 통해 이 클래스의 필드에 대한 getter를 자동 생성 +@Getter + +// Lombok을 통해 이 클래스의 필드에 대한 setter를 자동 생성 +@Setter + +// 매개 변수가 없는 기본 생성자를 자동 생성, JPA가 Entity 객체를 생성할 때 기본 생성자가 필요 +@NoArgsConstructor + +// 이 클래스가 JPA Entity임을 나타내며, DB 테이블과 매핑되는 클래스 +@Entity + +// 이 Entity가 매핑될 DB 테이블 이름을 지정, posts 테이블과 매핑 +@Table(name="posts") +public class Post extends GlobalEntity{ + + // 이 필드가 테이블의 기본키(Primary Key)임을 의미 + @Id + + // 기본키 값을 자동으로 생성하도록 설정 + // enerationType.IDENTITY는 DB의 AUTO_INCREMENT 기능을 사용하여 id를 자동 증가 + @GeneratedValue(strategy= GenerationType.IDENTITY) + private Long id; + + // title 필드를 DB의 post_title 컬럼과 매핑 + @Column(name = "post_title") + private String title; + + // content 필드를 DB의 post_content 컬럼과 매핑 + @Column(name = "post_content") + private String content; + + // 게시글을 생성할 때 제목과 내용을 받아 객체를 만들기 위한 생성자 + // id는 DB에 저장될 때 자동으로 생성되므로 생성자에서 받지 않음 + public Post(String title, String content) { + // 전달받은 title 값을 현재 객체의 title 필드에 저장 + this.title = title; + + // 전달받은 content 값을 현재 객체의 content 필드에 저장 + this.content = content; + } +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/DuplicatePostException.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/DuplicatePostException.java new file mode 100644 index 0000000..7e896ae --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/DuplicatePostException.java @@ -0,0 +1,15 @@ +package com.task.RestAPIServer.exception; + + +// 같은 제목과 내용의 게시글이 이미 존재할 때 사용할 사용자 정의 예외 클래스 +// RuntimeException을 상속했기 때문에 실행 중 발생하는 예외로 처리 +public class DuplicatePostException extends RuntimeException { + + // DuplicatePostException 객체를 생성할 때 호출되는 기본 생성자 + public DuplicatePostException() { + + // 부모 클래스인 RuntimeException의 생성자를 호출 + // 예외가 발생했을 때 e.getMessage()를 호출하면 "같은 제목과 내용의 게시글이 이미 존재합니다."가 반환 + super("같은 제목과 내용의 게시글이 이미 존재합니다."); + } +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/GlobalExceptionHandler.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..4fe9d03 --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/GlobalExceptionHandler.java @@ -0,0 +1,99 @@ +package com.task.RestAPIServer.exception; + +import com.task.RestAPIServer.dto.ErrorResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.time.LocalDateTime; + +// 로그 객체를 자동으로 생성 +// log.error("메시지", e)처럼 로그 남기기 가능 +@Slf4j + +// 전역 예외 처리 클래스임을 나타냄 +// Controller에서 발생한 예외를 이 클래스에서 공통 처리 +// @ControllerAdvice + @ResponseBody의 역할을 하며 JSON 형태의 응답 본문으로 전달 +@RestControllerAdvice +public class GlobalExceptionHandler { + + // PostNotFoundException 예외가 발생했을 때 이 메소드 실행 + // 예: 존자하지 않는 게시글 조회, 수정, 삭제 시도 + @ExceptionHandler(PostNotFoundException.class) + public ResponseEntity handlePostNotFoundException(PostNotFoundException e) { + + // 클라이언트에 반환할 에러 응답 DTO 생성 + ErrorResponse response = new ErrorResponse( + + // HTTP 상태 코드 숫자, NOT_FOUND는 404 + HttpStatus.NOT_FOUND.value(), + + // HTTP 상태 코드 이름, NOT_FOUND + HttpStatus.NOT_FOUND.name(), + + // 예외 객체에 들어 있는 메시지를 응답에 포함 + // 예: "해당 게시글을 찾을 수 없습니다." + e.getMessage(), + + // 에러가 발생한 현재 시간을 응답에 포함 + LocalDateTime.now() + ); + + // HTTP 404 Not Found 상태 코드와 함께 ErrorResponse를 응답 본문으로 반환 + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + } + + // PDuplicatePostException 예외가 발생했을 때 이 메소드 실행 + // 예: 같은 제목과 내용의 게시글 중복 생성 + @ExceptionHandler(DuplicatePostException.class) + public ResponseEntity handleDuplicatePostException(DuplicatePostException e) { + + // 클라이언트에 반환할 에러 응답 DTO 생성 + ErrorResponse response = new ErrorResponse( + // HTTP 상태 코드 숫자, BAD_REQUEST는 400 + HttpStatus.BAD_REQUEST.value(), + + // HTTP 상태 코드 이름, BAD_REQUEST + HttpStatus.BAD_REQUEST.name(), + + // 예외 객체에 들어있는 메시지를 응답에 포함 + // 예: "같은 제목과 내용의 게시글이 이미 존재합니다." + e.getMessage(), + + // 에러가 발생한 현재 시간을 응답에 포함 + LocalDateTime.now() + ); + + // HTTP 400 Bad Request 상태 코드와 함께 ErrorResponse를 응답 본문으로 반환 + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + // 위에서 따로 처리하지 않은 모든 예외를 처리하는 메소드 + // Exception은 대부분의 예외 클래스의 상위 클래스로, 예상치 못한 서버 오류를 마지막에 처리 + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(Exception e) { + + // 서버 내부 오류 내용을 로그로 남김 + log.error("서버 내부 오류 발생", e); + + // 클라이언트에 반환할 에러 응답 DTO를 생성 + ErrorResponse response = new ErrorResponse( + // HTTP 상태 코드 숫자, INTERNAL_SERVER_ERROR는 500 + HttpStatus.INTERNAL_SERVER_ERROR.value(), + + // HTTP 상태 코드 이름, INTERNAL_SERVER_ERROR + HttpStatus.INTERNAL_SERVER_ERROR.name(), + + // 클라이언트에 보여줄 일반적인 오류 메시지 + "서버 내부 오류가 발생했습니다.", + + // 에러가 발생한 현재 시간을 응답에 포함 + LocalDateTime.now() + ); + + // HTTP 500 Internal Server Error 상태 코드와 함께 ErrorResponse를 응답 본문으로 반환 + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/PostNotFoundException.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/PostNotFoundException.java new file mode 100644 index 0000000..38be3d5 --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/exception/PostNotFoundException.java @@ -0,0 +1,17 @@ +package com.task.RestAPIServer.exception; + + +// 게시글을 찾지 못했을 때 사용할 사용자 정의 예외 클래스 +// RuntimeException을 상속했기 때문에 실행 중 발생하는 예외로 처리 +public class PostNotFoundException extends RuntimeException { + + // PostNotFoundException 객체를 생성할 때 호출되는 생성자 + // 찾지 못한 게시글의 id를 매개변수로 받음 + public PostNotFoundException(Long id) { + + // 부모 클래스인 RuntimeException의 생성자를 호출 + // 예외가 발생했을 때 e.getMessage()를 호출하면 "해당 게시글이 존재하지 않습니다. id = 1" 같은 메시지 반환 + super("해당 게시글이 존재하지 않습니다. id = " + id); + } + +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/repository/PostRepository.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/repository/PostRepository.java new file mode 100644 index 0000000..21cecfa --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/repository/PostRepository.java @@ -0,0 +1,24 @@ +package com.task.RestAPIServer.repository; + +import com.task.RestAPIServer.entity.Post; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +// 이 인터페이스가 Repository의 역할을 한다는 것을 나타냄 +@Repository + +// Post: 이 Repository가 관리할 Entity의 타입 +// Long: Post Entity의 기본키인 id 필드의 타입 +public interface PostRepository extends JpaRepository { + + // 아래의 기본 메소드 사용 가능 + // save(post): 게시글 저장 + // findById(id): id로 게시글 조회 + // findAll(): 전체 게시글 조회 + // delete(post): 게시글 삭제 + // exitstById(id): id에 해당하는 게시글의 존재 여부 확인 + + // title 값과 content 값이 모두 일치하는 Post가 있는지 확인 + // 존재하면 true, 존재하지 않으면 false 반환 + boolean existsByTitleAndContent(String title, String content); +} diff --git a/spring-db/spring-db/src/main/java/com/task/RestAPIServer/service/PostService.java b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/service/PostService.java new file mode 100644 index 0000000..c60e76f --- /dev/null +++ b/spring-db/spring-db/src/main/java/com/task/RestAPIServer/service/PostService.java @@ -0,0 +1,107 @@ +package com.task.RestAPIServer.service; + +import com.task.RestAPIServer.dto.PostRequest; +import com.task.RestAPIServer.entity.Post; +import com.task.RestAPIServer.exception.DuplicatePostException; +import com.task.RestAPIServer.exception.PostNotFoundException; +import com.task.RestAPIServer.repository.PostRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +// final 필드를 대상으로 생성자를 자동 생성 +// postRepository를 생성자 주입 방식으로 주입받기 위해 사용 +@RequiredArgsConstructor + +// 이 클래스가 Service의 역할을 한다는 것을 나타냄 +// Service는 Controller와 Repository 사이에서 비즈니스 로직 처리 +@Service + +// 이 클래스의 메서드들이 하나의 트랜잭션 안에서 실행되도록 설정 +// DB 변경 작업 중 예외가 발생하면 변경 내용을 롤백하고, 정상 종료되면 커밋 +@Transactional +public class PostService { + + // 게시글 데이터를 DB에 저장, 조회, 수정, 삭자하기 위한 Repository + // final로 선언되었기 때문에 @RequiredArgsConstructor를 통해 생성자 주입 + private final PostRepository postRepository; + + // 게시글 생성 + // Controller에서 전달받은 PostRequest를 이용해 게시글을 생성하고 DB에 저장 + public Post save(PostRequest postRequest) { + + // 같은 제목과 내용의 게시글이 이미 존재하는지 확인 + if (postRepository.existsByTitleAndContent(postRequest.title(), postRequest.content())) { + + // 중복 게시글이 있으면 DuplicatePostException 예외 발생 + throw new DuplicatePostException(); + } + + // 요청 DTO에 담긴 title, content 값을 이용하여 Post Entity 객체 생성 + // id는 DB 저장 시 자동 생성됨 + Post post = new Post(postRequest.title(), postRequest.content()); + + // 생성한 Post 객체를 DB에 저장 + // 저장된 Entity 객체 반환 + return postRepository.save(post); + } + + // 조회 전용 트랜잭션으로 설정 + @Transactional(readOnly = true) + + // 단건 게시글 찾기 + public Post findById(Long id) { + + // Repository를 통해 id에 해당하는 게시글 조회 + // findById는 Optional 반환 + return postRepository.findById(id) + + // 게시글이 존재하지 않으면 PostNotFoundException 예외 발생 + .orElseThrow(() -> new PostNotFoundException(id)); + } + + // 조회 전용 트랜잭션으로 설정 + @Transactional(readOnly = true) + + // 전체 게시글 찾기 + public Page findAllPosts(Pageable pageable) { + + // Repository의 findAll(pageable)을 호출하여 페이징 처리된 게시글 목록 반환 + return postRepository.findAll(pageable); + } + + // 게시글 수정 + public Post update(Long id, PostRequest postRequest) { + + // id에 해당하는 게시글이 존재하는지 검색 + Post post = postRepository.findById(id) + + // 존재하지 않으면 PostNotFoundException 예외 발생 + .orElseThrow(() -> new PostNotFoundException(id)); + + // 요청 DTO에 담긴 title 값으로 기존 게시글의 제목 수정 + post.setTitle(postRequest.title()); + + // 요청 DTO에 담긴 content 값으로 기존 게시글의 내용 수정 + post.setContent(postRequest.content()); + + // 수정된 Post 객체를 DB에 다시 저장 + return postRepository.save(post); + } + + // 게시글 삭제 + public void delete(Long id) { + + // id에 해당하는 게시글이 존재하는지 확인 + if (!postRepository.existsById(id)) { + + // 삭제하려는 게시글이 존재하지 않으면 PostNotFoundException 예외를 발생 + throw new PostNotFoundException(id); + } + + // id에 해당하는 게시글을 DB에서 삭제 + postRepository.deleteById(id); + } +} diff --git a/spring-db/spring-db/src/main/resources/application.properties b/spring-db/spring-db/src/main/resources/application.properties new file mode 100644 index 0000000..40a9b77 --- /dev/null +++ b/spring-db/spring-db/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.application.name=RestAPIServer + +spring.output.ansi.enabled=always + +logging.level.org.springframework.web=DEBUG +logging.level.org.hibernate=DEBUG + +spring.jpa.hibernate.ddl-auto=update +spring.jpa.generate-ddl=true +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true + +spring.datasource.url=jdbc:mysql://localhost:3306/post_server +spring.datasource.username=${DB_USERNAME} +spring.datasource.password=${DB_PASSWORD} +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver \ No newline at end of file diff --git a/spring-db/spring-db/src/test/java/com/task/RestAPIServer/RestApiServerApplicationTests.java b/spring-db/spring-db/src/test/java/com/task/RestAPIServer/RestApiServerApplicationTests.java new file mode 100644 index 0000000..af7013f --- /dev/null +++ b/spring-db/spring-db/src/test/java/com/task/RestAPIServer/RestApiServerApplicationTests.java @@ -0,0 +1,13 @@ +package com.task.RestAPIServer; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RestApiServerApplicationTests { + + @Test + void contextLoads() { + } + +}