diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..4e933faa0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,249 @@ +# Created by https://www.toptal.com/developers/gitignore/api/java,intellij,macos,windows,visualstudiocode,gradle +# Edit at https://www.toptal.com/developers/gitignore?templates=java,intellij,macos,windows,visualstudiocode,gradle + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/java,intellij,macos,windows,visualstudiocode,gradle \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 000000000..9426139c2 --- /dev/null +++ b/HELP.md @@ -0,0 +1,31 @@ +# Read Me First +The following was discovered as part of building this project: + +* The original package name 'jehs.springboot-board-jpa' is invalid and this project uses 'jehs.springbootboardjpa' instead. + +# 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/docs/3.1.5/gradle-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.1.5/gradle-plugin/reference/html/#build-image) +* [Spring Web](https://docs.spring.io/spring-boot/docs/3.1.5/reference/htmlsingle/index.html#web) +* [Spring REST Docs](https://docs.spring.io/spring-restdocs/docs/current/reference/html5/) +* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.1.5/reference/htmlsingle/index.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 MySQL](https://spring.io/guides/gs/accessing-data-mysql/) +* [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/build.gradle b/build.gradle new file mode 100644 index 000000000..7bbed62e1 --- /dev/null +++ b/build.gradle @@ -0,0 +1,60 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.5' + id 'io.spring.dependency-management' version '1.1.3' + id 'org.asciidoctor.jvm.convert' version '3.3.2' +} + +group = 'jehs' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +ext { + set('snippetsDir', file("build/generated-snippets")) +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' +} + +tasks.named('bootBuildImage') { + builder = 'paketobuildpacks/builder-jammy-base:latest' +} + +tasks.named('test') { + outputs.dir snippetsDir + useJUnitPlatform() +} + +asciidoctor { + dependsOn test + inputs.dir snippetsDir +} + +bootJar { + enabled = true + dependsOn asciidoctor + copy { + from file('build/docs/asciidoc') + into file("src/main/resources/static/docs") + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..7f93135c4 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..3fa8f862f --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..1aa94a426 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 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. +# + +############################################################################## +# +# 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/HEAD/subprojects/plugins/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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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 + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# 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" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + 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, 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" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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 + +@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. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +: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/settings.gradle b/settings.gradle new file mode 100644 index 000000000..0795530c5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'springboot-board-jpa' diff --git a/src/docs/asciidoc/index.adoc b/src/docs/asciidoc/index.adoc new file mode 100644 index 000000000..a5a23c8d8 --- /dev/null +++ b/src/docs/asciidoc/index.adoc @@ -0,0 +1,47 @@ += REST Docs +:doctype: book +:icons: font +:source-highlighter: highlightjs +:toc: left +:toclevels: 2 +:sectlinks: + +ifndef::snippets[] +:snippets: build/generated-snippets +endif::[] + +=== 특정 게시글 조회 +http-request +include::{snippets}/getPostById/http-request.adoc[] +http-response +include::{snippets}/getPostById/http-response.adoc[] +response-fields +include::{snippets}/getPostById/response-fields.adoc[] + +=== 모든 게시글 조회 +http-request +include::{snippets}/getAllPosts/http-request.adoc[] +http-response +include::{snippets}/getAllPosts/http-response.adoc[] +response-fields +include::{snippets}/getAllPosts/response-fields.adoc[] + +=== 게시글 생성 +http-request +include::{snippets}/createPost/http-request.adoc[] +request-fields +include::{snippets}/createPost/request-fields.adoc[] +http-response +include::{snippets}/createPost/http-response.adoc[] +response-fields +include::{snippets}/createPost/response-fields.adoc[] + +=== 게시글 수정 +http-request +include::{snippets}/updatePost/http-request.adoc[] +request-fields +include::{snippets}/updatePost/request-fields.adoc[] +http-response +include::{snippets}/updatePost/http-response.adoc[] +response-fields +include::{snippets}/updatePost/response-fields.adoc[] \ No newline at end of file diff --git a/src/main/java/jehs/springbootboardjpa/SpringbootBoardJpaApplication.java b/src/main/java/jehs/springbootboardjpa/SpringbootBoardJpaApplication.java new file mode 100644 index 000000000..eb9d36555 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/SpringbootBoardJpaApplication.java @@ -0,0 +1,13 @@ +package jehs.springbootboardjpa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +public class SpringbootBoardJpaApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootBoardJpaApplication.class, args); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/config/ExceptionMessage.java b/src/main/java/jehs/springbootboardjpa/config/ExceptionMessage.java new file mode 100644 index 000000000..5116dbb5a --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/config/ExceptionMessage.java @@ -0,0 +1,12 @@ +package jehs.springbootboardjpa.config; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class ExceptionMessage { + + private final String error; + private final String message; +} diff --git a/src/main/java/jehs/springbootboardjpa/config/GlobalExceptionHandler.java b/src/main/java/jehs/springbootboardjpa/config/GlobalExceptionHandler.java new file mode 100644 index 000000000..871956fcc --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/config/GlobalExceptionHandler.java @@ -0,0 +1,35 @@ +package jehs.springbootboardjpa.config; + +import jehs.springbootboardjpa.exception.PostException; +import jehs.springbootboardjpa.exception.UserException; +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; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(PostException.class) + public ResponseEntity handlePostException(PostException e) { + log.warn(e.getMessage()); + ExceptionMessage exceptionMessage = new ExceptionMessage(e.getClass().getSimpleName(), e.getMessage()); + return new ResponseEntity<>(exceptionMessage, e.getHttpStatus()); + } + + @ExceptionHandler(UserException.class) + public ResponseEntity handleUserException(UserException e) { + log.warn(e.getMessage()); + ExceptionMessage exceptionMessage = new ExceptionMessage(e.getClass().getSimpleName(), e.getMessage()); + return new ResponseEntity<>(exceptionMessage, e.getHttpStatus()); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(Exception e) { + log.error(e.getMessage()); + ExceptionMessage exceptionMessage = new ExceptionMessage("Internal Server Error", "서버 내부 에러가 발생했습니다."); + return new ResponseEntity<>(exceptionMessage, HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/controller/PostController.java b/src/main/java/jehs/springbootboardjpa/controller/PostController.java new file mode 100644 index 000000000..43e45314b --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/controller/PostController.java @@ -0,0 +1,71 @@ +package jehs.springbootboardjpa.controller; + +import jehs.springbootboardjpa.dto.*; +import jehs.springbootboardjpa.entity.Post; +import jehs.springbootboardjpa.service.PostService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +public class PostController { + + private final PostService postService; + + @GetMapping("/api/v1/posts/{id}") + public ResponseEntity> getPost(@PathVariable(name = "id") Long postId) { + return new ResponseEntity<>( + new SuccessMessage<>( + "성공적으로 게시글이 조회되었습니다.", + postService.getPostResponseById(postId) + ), + HttpStatus.OK + ); + } + + @GetMapping("/api/v1/posts") + public ResponseEntity>> getAllPosts(@RequestParam(name = "page") int page, @RequestParam(name = "size") int size) { + return new ResponseEntity<>( + new SuccessMessage<>( + "성공적으로 모든 게시글이 조회되었습니다.", + postService.getAllPostsWithUser(page, size) + ), + HttpStatus.OK + ); + } + + @GetMapping("/api/v1/posts/cursor") + public ResponseEntity> getAllPostsByCursor(@RequestParam(name = "size") int size, @RequestParam(name = "cursorId") Long cursorId) { + return new ResponseEntity<>( + new SuccessMessage<>( + "성공적으로 모든 게시글이 조회되었습니다.", + postService.getAllPostsWithUserByCursor(size, cursorId) + ), + HttpStatus.OK + ); + } + + @PostMapping("/api/v1/posts") + public ResponseEntity> createPost(@RequestBody PostCreateRequest postCreateRequest) { + postService.createPost(postCreateRequest); + return new ResponseEntity<>( + new SuccessMessage<>( + "성공적으로 게시글이 생성되었습니다." + ), + HttpStatus.CREATED + ); + } + + @PatchMapping("/api/v1/posts/{id}") + public ResponseEntity> updatePost(@PathVariable(name = "id") Long postId, @RequestBody PostUpdateRequest postUpdateRequest) { + postService.updatePost(postId, postUpdateRequest); + return new ResponseEntity<>( + new SuccessMessage<>( + "성공적으로 게시글이 수정되었습니다." + ), + HttpStatus.OK + ); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/controller/SuccessMessage.java b/src/main/java/jehs/springbootboardjpa/controller/SuccessMessage.java new file mode 100644 index 000000000..40ddf11d7 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/controller/SuccessMessage.java @@ -0,0 +1,21 @@ +package jehs.springbootboardjpa.controller; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Getter; + +@Getter +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SuccessMessage { + + private final String message; + private T data; + + public SuccessMessage(String message, T data) { + this.message = message; + this.data = data; + } + + public SuccessMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/jehs/springbootboardjpa/dto/ListResponse.java b/src/main/java/jehs/springbootboardjpa/dto/ListResponse.java new file mode 100644 index 000000000..cd074af28 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/dto/ListResponse.java @@ -0,0 +1,21 @@ +package jehs.springbootboardjpa.dto; + +import lombok.Getter; +import org.springframework.data.domain.Page; + +import java.util.List; +import java.util.function.Function; + +@Getter +public class ListResponse { + + private final List content; + private final int totalPages; + private final long totalElements; + + public ListResponse(Page postsPage, Function function) { + this.content = postsPage.getContent().stream().map(function).toList(); + this.totalPages = postsPage.getTotalPages(); + this.totalElements = postsPage.getTotalElements(); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/dto/PostCreateRequest.java b/src/main/java/jehs/springbootboardjpa/dto/PostCreateRequest.java new file mode 100644 index 000000000..8a0aa59d7 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/dto/PostCreateRequest.java @@ -0,0 +1,25 @@ +package jehs.springbootboardjpa.dto; + +import jehs.springbootboardjpa.entity.Post; +import jehs.springbootboardjpa.entity.User; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class PostCreateRequest { + + private final String title; + private final String content; + private final Long userId; + private final Post.PostType postType; + + public Post toEntity(User user) { + return Post.builder() + .title(title) + .content(content) + .user(user) + .postType(postType) + .build(); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/dto/PostResponse.java b/src/main/java/jehs/springbootboardjpa/dto/PostResponse.java new file mode 100644 index 000000000..78e2ad0ed --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/dto/PostResponse.java @@ -0,0 +1,28 @@ +package jehs.springbootboardjpa.dto; + +import jehs.springbootboardjpa.entity.Post; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +public class PostResponse { + + private final Long id; + private final String title; + private final String content; + private final Post.PostType postType; + private final LocalDateTime createdAt; + private final LocalDateTime updatedAt; + private final UserResponse userResponse; + + public PostResponse(Post post) { + this.id = post.getId(); + this.title = post.getTitle(); + this.content = post.getContent(); + this.postType = post.getPostType(); + this.createdAt = post.getCreatedAt(); + this.updatedAt = post.getUpdatedAt(); + this.userResponse = new UserResponse(post.getUser()); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/dto/PostUpdateRequest.java b/src/main/java/jehs/springbootboardjpa/dto/PostUpdateRequest.java new file mode 100644 index 000000000..eff838466 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/dto/PostUpdateRequest.java @@ -0,0 +1,13 @@ +package jehs.springbootboardjpa.dto; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class PostUpdateRequest { + + private final String title; + private final String content; + private final Long userId; +} diff --git a/src/main/java/jehs/springbootboardjpa/dto/PostsCursorResponse.java b/src/main/java/jehs/springbootboardjpa/dto/PostsCursorResponse.java new file mode 100644 index 000000000..24be6c9f5 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/dto/PostsCursorResponse.java @@ -0,0 +1,19 @@ +package jehs.springbootboardjpa.dto; + +import jehs.springbootboardjpa.entity.Post; +import lombok.Getter; +import org.springframework.data.domain.Slice; + +import java.util.List; + +@Getter +public class PostsCursorResponse { + + private final List content; + private final boolean hasNext; + + public PostsCursorResponse(Slice postSlice) { + this.content = postSlice.getContent().stream().map(PostResponse::new).toList(); + this.hasNext = postSlice.hasNext(); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/dto/UserResponse.java b/src/main/java/jehs/springbootboardjpa/dto/UserResponse.java new file mode 100644 index 000000000..cf96e2d6b --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/dto/UserResponse.java @@ -0,0 +1,20 @@ +package jehs.springbootboardjpa.dto; + +import jehs.springbootboardjpa.entity.User; +import lombok.Getter; + +@Getter +public class UserResponse { + + private final Long id; + private final String name; + private final Long age; + private final String hobby; + + public UserResponse(User user) { + this.id = user.getId(); + this.name = user.getName(); + this.age = user.getAge().getValue(); + this.hobby = user.getHobby(); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/entity/BaseEntity.java b/src/main/java/jehs/springbootboardjpa/entity/BaseEntity.java new file mode 100644 index 000000000..992ee7930 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/entity/BaseEntity.java @@ -0,0 +1,26 @@ +package jehs.springbootboardjpa.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +@MappedSuperclass +public abstract class BaseEntity { + + @Builder.Default + @Column(name = "created_at", columnDefinition = "datetime") + private LocalDateTime createdAt = LocalDateTime.now(); + @Builder.Default + @Column(name = "updated_at", columnDefinition = "datetime") + private LocalDateTime updatedAt = LocalDateTime.now(); + @Column(name = "deleted_at", columnDefinition = "datetime") + private LocalDateTime deletedAt; + + public void setUpdatedAt(LocalDateTime updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/src/main/java/jehs/springbootboardjpa/entity/Post.java b/src/main/java/jehs/springbootboardjpa/entity/Post.java new file mode 100644 index 000000000..6569c73c0 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/entity/Post.java @@ -0,0 +1,56 @@ +package jehs.springbootboardjpa.entity; + +import jakarta.persistence.*; +import jehs.springbootboardjpa.dto.PostUpdateRequest; +import jehs.springbootboardjpa.exception.PostErrorMessage; +import jehs.springbootboardjpa.exception.PostException; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Entity +@Table(name = "posts") +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Post extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "title", length = 59) + private String title; + + @Column(name = "content", length = 1000) + private String content; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @Enumerated(EnumType.STRING) + @Column(name = "post_type") + private PostType postType; + + public void updatePost(PostUpdateRequest postUpdateRequest, User user) { + validateUser(user); + this.title = postUpdateRequest.getTitle(); + this.content = postUpdateRequest.getContent(); + this.setUpdatedAt(LocalDateTime.now()); + } + + private void validateUser(User updateUser) { + if (!updateUser.isSameName(this.getUser().getName())) { + throw new PostException(PostErrorMessage.NOT_POST_BY_USER); + } + } + + public enum PostType { + FREE, INFO, MARKET, EMPLOYMENT + } +} diff --git a/src/main/java/jehs/springbootboardjpa/entity/User.java b/src/main/java/jehs/springbootboardjpa/entity/User.java new file mode 100644 index 000000000..5202c72b3 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/entity/User.java @@ -0,0 +1,33 @@ +package jehs.springbootboardjpa.entity; + +import jakarta.persistence.*; +import jehs.springbootboardjpa.entity.vo.Age; +import lombok.Getter; + +import java.util.List; + +@Entity +@Table(name = "users") +@Getter +public class User extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name", nullable = false, length = 59) + private String name; + + @Embedded + private Age age; + + @Column(name = "hobby", length = 59) + private String hobby; + + @OneToMany(mappedBy = "user", fetch = FetchType.LAZY) + private List posts; + + public boolean isSameName(String name) { + return this.getName().equals(name); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/entity/vo/Age.java b/src/main/java/jehs/springbootboardjpa/entity/vo/Age.java new file mode 100644 index 000000000..c027f93fe --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/entity/vo/Age.java @@ -0,0 +1,27 @@ +package jehs.springbootboardjpa.entity.vo; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jehs.springbootboardjpa.exception.UserErrorMessage; +import jehs.springbootboardjpa.exception.UserException; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@Embeddable +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Age { + + private static final Long MIN_AGE = 0L; + + @Column(name = "age", nullable = false) + private Long value; + + public Age(Long value) { + if (value < MIN_AGE) { + throw new UserException(UserErrorMessage.INVALID_AGE); + } + this.value = value; + } +} diff --git a/src/main/java/jehs/springbootboardjpa/exception/PostErrorMessage.java b/src/main/java/jehs/springbootboardjpa/exception/PostErrorMessage.java new file mode 100644 index 000000000..6cac99cfc --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/exception/PostErrorMessage.java @@ -0,0 +1,16 @@ +package jehs.springbootboardjpa.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum PostErrorMessage { + + NOT_FOUND("존재하지 않는 게시글입니다.", HttpStatus.NOT_FOUND), + NOT_POST_BY_USER("작성자의 게시글이 아닙니다.", HttpStatus.BAD_REQUEST); + + private final String message; + private final HttpStatus httpStatus; +} diff --git a/src/main/java/jehs/springbootboardjpa/exception/PostException.java b/src/main/java/jehs/springbootboardjpa/exception/PostException.java new file mode 100644 index 000000000..5de6fa86a --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/exception/PostException.java @@ -0,0 +1,17 @@ +package jehs.springbootboardjpa.exception; + +import org.springframework.http.HttpStatus; + +public class PostException extends RuntimeException { + + private final HttpStatus httpStatus; + + public PostException(PostErrorMessage postErrorMessage) { + super(postErrorMessage.getMessage()); + this.httpStatus = postErrorMessage.getHttpStatus(); + } + + public HttpStatus getHttpStatus() { + return httpStatus; + } +} diff --git a/src/main/java/jehs/springbootboardjpa/exception/UserErrorMessage.java b/src/main/java/jehs/springbootboardjpa/exception/UserErrorMessage.java new file mode 100644 index 000000000..4c9da4141 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/exception/UserErrorMessage.java @@ -0,0 +1,15 @@ +package jehs.springbootboardjpa.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum UserErrorMessage { + NOT_FOUND("존재하지 않는 회원입니다.", HttpStatus.NOT_FOUND), + INVALID_AGE("나이는 0보다 작을 수 없습니다.", HttpStatus.BAD_REQUEST); + + private final String message; + private final HttpStatus httpStatus; +} diff --git a/src/main/java/jehs/springbootboardjpa/exception/UserException.java b/src/main/java/jehs/springbootboardjpa/exception/UserException.java new file mode 100644 index 000000000..5c1311791 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/exception/UserException.java @@ -0,0 +1,17 @@ +package jehs.springbootboardjpa.exception; + +import org.springframework.http.HttpStatus; + +public class UserException extends RuntimeException { + + private final HttpStatus httpStatus; + + public UserException(UserErrorMessage userErrorMessage) { + super(userErrorMessage.getMessage()); + this.httpStatus = userErrorMessage.getHttpStatus(); + } + + public HttpStatus getHttpStatus() { + return httpStatus; + } +} diff --git a/src/main/java/jehs/springbootboardjpa/repository/PostRepository.java b/src/main/java/jehs/springbootboardjpa/repository/PostRepository.java new file mode 100644 index 000000000..3467b6250 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/repository/PostRepository.java @@ -0,0 +1,22 @@ +package jehs.springbootboardjpa.repository; + +import jehs.springbootboardjpa.entity.Post; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.Optional; + +public interface PostRepository extends JpaRepository { + + @Query("select p from Post p join fetch p.user where p.id = :id") + Optional findByIdWithUser(Long id); + + @Query("select p from Post p join fetch p.user") + Page findAllWithUser(Pageable pageable); + + @Query("select p from Post p join fetch p.user where p.id > :cursorId") + Slice findAllWithUserByCursor(Long cursorId, Pageable pageable); +} diff --git a/src/main/java/jehs/springbootboardjpa/repository/UserRepository.java b/src/main/java/jehs/springbootboardjpa/repository/UserRepository.java new file mode 100644 index 000000000..2b0cbade7 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/repository/UserRepository.java @@ -0,0 +1,7 @@ +package jehs.springbootboardjpa.repository; + +import jehs.springbootboardjpa.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/src/main/java/jehs/springbootboardjpa/service/PostService.java b/src/main/java/jehs/springbootboardjpa/service/PostService.java new file mode 100644 index 000000000..d07fa8d38 --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/service/PostService.java @@ -0,0 +1,58 @@ +package jehs.springbootboardjpa.service; + +import jehs.springbootboardjpa.dto.*; +import jehs.springbootboardjpa.entity.Post; +import jehs.springbootboardjpa.entity.User; +import jehs.springbootboardjpa.exception.PostErrorMessage; +import jehs.springbootboardjpa.exception.PostException; +import jehs.springbootboardjpa.repository.PostRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class PostService { + + private final PostRepository postRepository; + private final UserService userService; + + @Transactional + public void createPost(PostCreateRequest postCreateRequest) { + User user = userService.getUserById(postCreateRequest.getUserId()); + postRepository.save(postCreateRequest.toEntity(user)); + } + + @Transactional + public void updatePost(Long postId, PostUpdateRequest postUpdateRequest) { + Post post = getPostByIdWithUser(postId); + User user = userService.getUserById(postUpdateRequest.getUserId()); + post.updatePost(postUpdateRequest, user); + } + + @Transactional(readOnly = true) + public PostResponse getPostResponseById(Long postId) { + Post postById = getPostByIdWithUser(postId); + return new PostResponse(postById); + } + + public Post getPostByIdWithUser(Long postId) { + return postRepository.findByIdWithUser(postId) + .orElseThrow(() -> new PostException(PostErrorMessage.NOT_FOUND)); + } + + @Transactional(readOnly = true) + public ListResponse getAllPostsWithUser(int page, int size) { + return new ListResponse<>( + postRepository.findAllWithUser(PageRequest.of(page, size)), PostResponse::new + ); + } + + @Transactional(readOnly = true) + public PostsCursorResponse getAllPostsWithUserByCursor(int size, Long cursorId) { + return new PostsCursorResponse( + postRepository.findAllWithUserByCursor(cursorId, PageRequest.of(0, size)) + ); + } +} diff --git a/src/main/java/jehs/springbootboardjpa/service/UserService.java b/src/main/java/jehs/springbootboardjpa/service/UserService.java new file mode 100644 index 000000000..85c45623e --- /dev/null +++ b/src/main/java/jehs/springbootboardjpa/service/UserService.java @@ -0,0 +1,20 @@ +package jehs.springbootboardjpa.service; + +import jehs.springbootboardjpa.entity.User; +import jehs.springbootboardjpa.exception.UserErrorMessage; +import jehs.springbootboardjpa.exception.UserException; +import jehs.springbootboardjpa.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class UserService { + + private final UserRepository userRepository; + + public User getUserById(Long userId) { + return userRepository.findById(userId) + .orElseThrow(() -> new UserException(UserErrorMessage.NOT_FOUND)); + } +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 000000000..ee5a640c2 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,19 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/default_db?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8&useSSL=true + username: root + password: local59! + jpa: + open-in-view: false + database: mysql + show-sql: true + hibernate: + ddl-auto: update + properties: + hibernate: + format_sql: true + defer-datasource-initialization: true + sql: + init: + mode: always \ No newline at end of file diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql new file mode 100644 index 000000000..e4ae30d57 --- /dev/null +++ b/src/main/resources/data.sql @@ -0,0 +1,3 @@ +INSERT INTO users (id, created_at, deleted_at, updated_at, age, hobby, name) +SELECT 1, '2023-11-23 10:45:12', null, '2023-11-23 10:45:13', 59, 'platypus', 'ogu' +WHERE NOT EXISTS (SELECT * FROM users WHERE id = 1); \ No newline at end of file diff --git a/src/main/resources/static/docs/index.html b/src/main/resources/static/docs/index.html new file mode 100644 index 000000000..aa4056cd4 --- /dev/null +++ b/src/main/resources/static/docs/index.html @@ -0,0 +1,1142 @@ + + + + + + + +REST Docs + + + + + + +
+
+

특정 게시글 조회

+
+

http-request

+
+
+
+
GET /api/v1/posts/6237 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Host: localhost:8080
+
+
+
+

http-response

+
+
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 399
+
+{
+  "message" : "성공적으로 게시글이 조회되었습니다.",
+  "data" : {
+    "id" : 6237,
+    "title" : "Test Title",
+    "content" : "Test Content",
+    "postType" : "FREE",
+    "createdAt" : "2023-11-24T10:53:30.380548",
+    "updatedAt" : "2023-11-24T10:53:30.401951",
+    "userResponse" : {
+      "id" : 1,
+      "name" : "ogu",
+      "age" : 59,
+      "hobby" : "platypus"
+    }
+  }
+}
+
+
+
+

response-fields

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

message

String

성공 메시지

data.id

Number

게시글 아이디

data.title

String

게시글 제목

data.content

String

게시글 내용

data.postType

String

게시글 종류

data.createdAt

String

게시글 생성시간

data.updatedAt

String

게시글 수정시간

data.userResponse.id

Number

게시자 아이디

data.userResponse.name

String

게시자 이름

data.userResponse.age

Number

게시자 나이

data.userResponse.hobby

String

게시자 취미

+
+
+

모든 게시글 조회

+
+

http-request

+
+
+
+
GET /api/v1/posts?page=3&size=10 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Host: localhost:8080
+
+
+
+

http-response

+
+
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 4051
+
+{
+  "message" : "성공적으로 모든 게시글이 조회되었습니다.",
+  "data" : {
+    "content" : [ {
+      "id" : 6670,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.579316",
+      "updatedAt" : "2023-11-24T10:53:33.579441",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6671,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.580615",
+      "updatedAt" : "2023-11-24T10:53:33.580661",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6672,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.581813",
+      "updatedAt" : "2023-11-24T10:53:33.581981",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6673,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.584492",
+      "updatedAt" : "2023-11-24T10:53:33.584636",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6674,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.58606",
+      "updatedAt" : "2023-11-24T10:53:33.586121",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6675,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.587548",
+      "updatedAt" : "2023-11-24T10:53:33.587629",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6676,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.588448",
+      "updatedAt" : "2023-11-24T10:53:33.588501",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6677,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.589113",
+      "updatedAt" : "2023-11-24T10:53:33.589152",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6678,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.589802",
+      "updatedAt" : "2023-11-24T10:53:33.58987",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    }, {
+      "id" : 6679,
+      "title" : "Test Title",
+      "content" : "Test Content",
+      "postType" : "FREE",
+      "createdAt" : "2023-11-24T10:53:33.59047",
+      "updatedAt" : "2023-11-24T10:53:33.59052",
+      "userResponse" : {
+        "id" : 1,
+        "name" : "ogu",
+        "age" : 59,
+        "hobby" : "platypus"
+      }
+    } ],
+    "pageable" : {
+      "pageNumber" : 3,
+      "pageSize" : 10,
+      "sort" : {
+        "empty" : true,
+        "unsorted" : true,
+        "sorted" : false
+      },
+      "offset" : 30,
+      "paged" : true,
+      "unpaged" : false
+    },
+    "totalPages" : 10,
+    "totalElements" : 100,
+    "last" : false,
+    "size" : 10,
+    "number" : 3,
+    "sort" : {
+      "empty" : true,
+      "unsorted" : true,
+      "sorted" : false
+    },
+    "numberOfElements" : 10,
+    "first" : false,
+    "empty" : false
+  }
+}
+
+
+
+

response-fields

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

message

String

성공 메시지

data.content[].id

Number

게시글 아이디

data.content[].title

String

게시글 제목

data.content[].content

String

게시글 내용

data.content[].postType

String

게시글 종류

data.content[].createdAt

String

게시글 생성시간

data.content[].updatedAt

String

게시글 수정시간

data.content[].userResponse.id

Number

게시자 아이디

data.content[].userResponse.name

String

게시자 이름

data.content[].userResponse.age

Number

게시자 나이

data.content[].userResponse.hobby

String

게시자 취미

data.pageable

Object

페이징 정보

data.pageable.pageNumber

Number

현재 페이지 번호

data.pageable.pageSize

Number

페이지 크기

data.pageable.sort

Object

정렬 정보

data.pageable.sort.empty

Boolean

정렬이 비어있는지 여부

data.pageable.sort.unsorted

Boolean

정렬되지 않았는지 여부

data.pageable.sort.sorted

Boolean

정렬되었는지 여부

data.pageable.offset

Number

현재 페이지의 시작 오프셋

data.pageable.unpaged

Boolean

페이징되지 않은지 여부

data.pageable.paged

Boolean

페이징된지 여부

data.last

Boolean

마지막 페이지 여부

data.totalPages

Number

전체 페이지 수

data.totalElements

Number

전체 엘리먼트 수

data.first

Boolean

첫 번째 페이지 여부

data.size

Number

현재 페이지의 엘리먼트 수

data.number

Number

현재 페이지 번호

data.sort

Object

정렬 정보

data.sort.empty

Boolean

정렬이 비어있는지 여부

data.sort.unsorted

Boolean

정렬되지 않았는지 여부

data.sort.sorted

Boolean

정렬되었는지 여부

data.numberOfElements

Number

현재 페이지의 엘리먼트 수

data.empty

Boolean

데이터가 비어있는지 여부

+
+
+

게시글 생성

+
+

http-request

+
+
+
+
POST /api/v1/posts HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 97
+Host: localhost:8080
+
+{
+  "title" : "Test Title",
+  "content" : "Test Content",
+  "userId" : 1,
+  "postType" : "FREE"
+}
+
+
+
+

request-fields

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

title

String

게시글 제목

content

String

게시글 내용

userId

Number

게시자 아이디

postType

String

게시글 종류

+
+

http-response

+
+
+
+
HTTP/1.1 201 Created
+Content-Type: application/json
+Content-Length: 71
+
+{
+  "message" : "성공적으로 게시글이 생성되었습니다."
+}
+
+
+
+

response-fields

+
+ +++++ + + + + + + + + + + + + + + +
PathTypeDescription

message

String

성공 메시지

+
+
+

게시글 수정

+
+

http-request

+
+
+
+
PATCH /api/v1/posts/6238 HTTP/1.1
+Content-Type: application/json;charset=UTF-8
+Content-Length: 80
+Host: localhost:8080
+
+{
+  "title" : "Updated Title",
+  "content" : "Updated Content",
+  "userId" : 1
+}
+
+
+
+

request-fields

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
PathTypeDescription

title

String

게시글 제목

content

String

게시글 내용

userId

Number

게시자 아이디

+
+

http-response

+
+
+
+
HTTP/1.1 200 OK
+Content-Type: application/json
+Content-Length: 71
+
+{
+  "message" : "성공적으로 게시글이 수정되었습니다."
+}
+
+
+
+

response-fields

+
+ +++++ + + + + + + + + + + + + + + +
PathTypeDescription

message

String

성공 메시지

+
+
+ + + + + + \ No newline at end of file diff --git a/src/test/java/jehs/springbootboardjpa/controller/PostControllerTest.java b/src/test/java/jehs/springbootboardjpa/controller/PostControllerTest.java new file mode 100644 index 000000000..1ad1793db --- /dev/null +++ b/src/test/java/jehs/springbootboardjpa/controller/PostControllerTest.java @@ -0,0 +1,263 @@ +package jehs.springbootboardjpa.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jehs.springbootboardjpa.dto.PostCreateRequest; +import jehs.springbootboardjpa.dto.PostUpdateRequest; +import jehs.springbootboardjpa.entity.Post; +import jehs.springbootboardjpa.entity.User; +import jehs.springbootboardjpa.repository.PostRepository; +import jehs.springbootboardjpa.repository.UserRepository; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; +import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@AutoConfigureRestDocs +class PostControllerTest { + + @Autowired + private MockMvc mockMvc; + @Autowired + private PostRepository postRepository; + @Autowired + private UserRepository userRepository; + + @BeforeEach + void setUp() { + postRepository.deleteAll(); + } + + @Test + @DisplayName("ID로 Post를 조회할 수 있습니다.") + @Transactional + void testGetPostById() throws Exception { + // Given + User user = userRepository.findById(1L).orElseThrow(); + Post post = postRepository.save(Post.builder() + .title("Test Title") + .content("Test Content") + .user(user) + .postType(Post.PostType.FREE) + .build() + ); + + // When + ResultActions perform = mockMvc.perform(get("/api/v1/posts/{postId}", post.getId()) + .contentType(MediaType.APPLICATION_JSON)); + + // Then + perform + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("성공적으로 게시글이 조회되었습니다.")) + .andExpect(jsonPath("$.data.id").value(post.getId())) + .andExpect(jsonPath("$.data.title").value(post.getTitle())) + .andExpect(jsonPath("$.data.content").value(post.getContent())) + .andExpect(jsonPath("$.data.postType").value(post.getPostType().toString())) + .andExpect(jsonPath("$.data.userResponse.id").value(user.getId())) + .andExpect(jsonPath("$.data.userResponse.name").value(user.getName())) + .andExpect(jsonPath("$.data.userResponse.age").value(user.getAge())) + .andExpect(jsonPath("$.data.userResponse.hobby").value(user.getHobby())) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) + .andDo(document("getPostById", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + pathParameters(parameterWithName("postId").description("게시글 아이디")), + responseFields( + fieldWithPath("message").description("성공 메시지"), + fieldWithPath("data.id").description("게시글 아이디"), + fieldWithPath("data.title").description("게시글 제목"), + fieldWithPath("data.content").description("게시글 내용"), + fieldWithPath("data.postType").description("게시글 종류"), + fieldWithPath("data.createdAt").description("게시글 생성시간"), + fieldWithPath("data.updatedAt").description("게시글 수정시간"), + fieldWithPath("data.userResponse.id").description("게시자 아이디"), + fieldWithPath("data.userResponse.name").description("게시자 이름"), + fieldWithPath("data.userResponse.age").description("게시자 나이"), + fieldWithPath("data.userResponse.hobby").description("게시자 취미") + )) + ); + } + + @DisplayName("페이지네이션을 통해 모든 게시글을 조회할 수 있습니다") + @CsvSource({ + "0, 10", + "0, 30", + "1, 20", + "2, 10", + "3, 10", + }) + @ParameterizedTest + @Transactional + void testGetPostPagination(int page, int size) throws Exception { + // Given + User user = userRepository.findById(1L).orElseThrow(); + List postList = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + postList.add( + postRepository.save(Post.builder() + .title("Test Title") + .content("Test Content") + .user(user) + .postType(Post.PostType.FREE) + .build() + ) + ); + } + + // When + ResultActions perform = mockMvc.perform(get("/api/v1/posts") + .param("page", String.valueOf(page)) + .param("size", String.valueOf(size)) + .contentType(MediaType.APPLICATION_JSON)); + + // Then + final int index = page * size; + Post post = postList.get(index); + perform + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("성공적으로 모든 게시글이 조회되었습니다.")) + .andExpect(jsonPath("$.data.content[0].id").value(post.getId())) + .andExpect(jsonPath("$.data.content[0].title").value(post.getTitle())) + .andExpect(jsonPath("$.data.content[0].content").value(post.getContent())) + .andExpect(jsonPath("$.data.content[0].postType").value(post.getPostType().toString())) + .andExpect(jsonPath("$.data.content[0].userResponse.id").value(user.getId())) + .andExpect(jsonPath("$.data.content[0].userResponse.name").value(user.getName())) + .andExpect(jsonPath("$.data.content[0].userResponse.age").value(user.getAge())) + .andExpect(jsonPath("$.data.content[0].userResponse.hobby").value(user.getHobby())) + .andExpect(jsonPath("$.data.content", Matchers.hasSize(size))) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) + .andDo(document("getAllPosts", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + responseFields( + fieldWithPath("message").description("성공 메시지"), + fieldWithPath("data.content[].id").description("게시글 아이디"), + fieldWithPath("data.content[].title").description("게시글 제목"), + fieldWithPath("data.content[].content").description("게시글 내용"), + fieldWithPath("data.content[].postType").description("게시글 종류"), + fieldWithPath("data.content[].createdAt").description("게시글 생성시간"), + fieldWithPath("data.content[].updatedAt").description("게시글 수정시간"), + fieldWithPath("data.content[].userResponse.id").description("게시자 아이디"), + fieldWithPath("data.content[].userResponse.name").description("게시자 이름"), + fieldWithPath("data.content[].userResponse.age").description("게시자 나이"), + fieldWithPath("data.content[].userResponse.hobby").description("게시자 취미"), + fieldWithPath("data.totalPages").description("전체 페이지 수"), + fieldWithPath("data.totalElements").description("전체 엘리먼트 수") + )) + ); + } + + @Test + @DisplayName("게시글을 생성할 수 있습니다.") + @Transactional + void testCreatePost() throws Exception { + // Given + final String testTitle = "Test Title"; + PostCreateRequest postCreateRequest = new PostCreateRequest( + testTitle, + "Test Content", + 1L, + Post.PostType.FREE + ); + + // When + ResultActions perform = mockMvc.perform(post("/api/v1/posts") + .contentType(MediaType.APPLICATION_JSON) + .content(new ObjectMapper().writeValueAsString(postCreateRequest))); + + // Then + perform + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.message").value("성공적으로 게시글이 생성되었습니다.")) + .andDo(document("createPost", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("title").description("게시글 제목"), + fieldWithPath("content").description("게시글 내용"), + fieldWithPath("userId").description("게시자 아이디"), + fieldWithPath("postType").description("게시글 종류") + ), + responseFields( + fieldWithPath("message").description("성공 메시지") + ) + ) + ); + List postList = postRepository.findAll(); + assertThat(postList).hasSize(1); + } + + @Test + @DisplayName("게시글을 수정할 수 있습니다.") + @Transactional + void testUpdatePost() throws Exception { + // Given + User user = userRepository.findById(1L).orElseThrow(); + Post post = postRepository.save(Post.builder() + .title("Test Title") + .content("Test Content") + .user(user) + .postType(Post.PostType.FREE) + .build() + ); + final String updatedTitle = "Updated Title"; + PostUpdateRequest postUpdateRequest = new PostUpdateRequest( + updatedTitle, + "Updated Content", + 1L + ); + + // When + ResultActions perform = mockMvc.perform(patch("/api/v1/posts/{postId}", post.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(new ObjectMapper().writeValueAsString(postUpdateRequest))); + + // Then + perform + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("성공적으로 게시글이 수정되었습니다.")) + .andDo(document("updatePost", + preprocessRequest(prettyPrint()), + preprocessResponse(prettyPrint()), + requestFields( + fieldWithPath("title").description("게시글 제목"), + fieldWithPath("content").description("게시글 내용"), + fieldWithPath("userId").description("게시자 아이디") + ), + responseFields( + fieldWithPath("message").description("성공 메시지") + ) + ) + ); + Optional foundPost = postRepository.findById(post.getId()); + assertThat(foundPost).isNotEmpty(); + assertThat(foundPost.get().getTitle()).isEqualTo(updatedTitle); + } +}