diff --git a/springdb/.gitattributes b/springdb/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/springdb/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/springdb/.gitignore b/springdb/.gitignore new file mode 100644 index 0000000..a00fec8 --- /dev/null +++ b/springdb/.gitignore @@ -0,0 +1,39 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +.env diff --git a/springdb/README.md b/springdb/README.md new file mode 100644 index 0000000..f085430 --- /dev/null +++ b/springdb/README.md @@ -0,0 +1,42 @@ +# 과제명 +게시판 + DB연동 + +## ⚙️ 실행 방법 +1. mysql 생성 후 SCHEMAS 생성(board) +2. .env 에 DB정보 입력 +3. SpringdbApplication 실행 + +## 💡 작업 내용 +- 게시글 CRUD 구성 +- 댓글 CRUD 구성 +- MYSQL 연동 +- JPA사용 + +# API 명세 + +| Method | URI | 설명 | +|--------|-----|------| +| POST | /post | 게시글 생성 | +| GET | /post | 게시글 목록 조회 | +| GET | /post/{id} | 게시글 단건 조회 | +| PUT | /post/{id} | 게시글 수정 | +| DELETE | /post/{id} | 게시글 삭제 | +|Post|/post/{id}/comment| 댓글 추가| +|GET|/post/{id}/comment|댓글 전체 조회| +|GET|post/{id}/comment/{commentId}|댓글 단건 조회| +|PUT|post/{id}/comment/{commentId}|댓글 수정| +|DELETE|post/{id}/comment/{commentId}|댓글 삭제| + + +# API 성공 세부 사항 +- 200-1: 게시물 등록 성공 +- 200-2: 게시물 단건 조회 선공 +- 200-3: 게시물 수정 조회 선공 +- 200-4: 게시물 삭제 선공 +- 200-5: 게시물 전체 조회 선공 + +## 🤔 느낀 점 / 어려웠던 점 +- 저번주에 피드백 주신 내용을 중점으로 작성해보았습니다 +- jpa를 사용하더라도 DB 구조 설계에 대해서 더욱 학습이 필요하다는 것을 느끼게 되었습니다. +- 게시물도 처음부터 작성해보고 댓글도 만들어보면서 dto의 흐름이나 전체적인 흐름을 알 수 있었습니다. +- domain 계층구조를 사용해서 작성해보았습니다. 이것이 관리하거나 찾기가 더욱 편리한것 같습니다 . \ No newline at end of file diff --git a/springdb/build.gradle b/springdb/build.gradle new file mode 100644 index 0000000..5471347 --- /dev/null +++ b/springdb/build.gradle @@ -0,0 +1,39 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.0.6' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.board' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-webmvc' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test' + testImplementation 'org.springframework.boot:spring-boot-starter-validation-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testCompileOnly 'org.projectlombok:lombok' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testAnnotationProcessor 'org.projectlombok:lombok' + implementation 'com.mysql:mysql-connector-j:8.0.33' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/springdb/docs/Comment/deleteComment.png b/springdb/docs/Comment/deleteComment.png new file mode 100644 index 0000000..b976b99 Binary files /dev/null and b/springdb/docs/Comment/deleteComment.png differ diff --git a/springdb/docs/Comment/getAllComment.png b/springdb/docs/Comment/getAllComment.png new file mode 100644 index 0000000..038e8e4 Binary files /dev/null and b/springdb/docs/Comment/getAllComment.png differ diff --git a/springdb/docs/Comment/getOneComment.png b/springdb/docs/Comment/getOneComment.png new file mode 100644 index 0000000..84751e7 Binary files /dev/null and b/springdb/docs/Comment/getOneComment.png differ diff --git a/springdb/docs/Comment/newComment.png b/springdb/docs/Comment/newComment.png new file mode 100644 index 0000000..9fedb94 Binary files /dev/null and b/springdb/docs/Comment/newComment.png differ diff --git a/springdb/docs/Comment/updateComment.png b/springdb/docs/Comment/updateComment.png new file mode 100644 index 0000000..507a26b Binary files /dev/null and b/springdb/docs/Comment/updateComment.png differ diff --git a/springdb/docs/DB/PostDB.png b/springdb/docs/DB/PostDB.png new file mode 100644 index 0000000..85ade04 Binary files /dev/null and b/springdb/docs/DB/PostDB.png differ diff --git a/springdb/docs/DB/commentDB.png b/springdb/docs/DB/commentDB.png new file mode 100644 index 0000000..a8ccf11 Binary files /dev/null and b/springdb/docs/DB/commentDB.png differ diff --git a/springdb/docs/Post/PostPaging.png b/springdb/docs/Post/PostPaging.png new file mode 100644 index 0000000..bd311bd Binary files /dev/null and b/springdb/docs/Post/PostPaging.png differ diff --git a/springdb/docs/Post/deletePost.png b/springdb/docs/Post/deletePost.png new file mode 100644 index 0000000..0d9ebe2 Binary files /dev/null and b/springdb/docs/Post/deletePost.png differ diff --git a/springdb/docs/Post/getAll.png b/springdb/docs/Post/getAll.png new file mode 100644 index 0000000..6165ae9 Binary files /dev/null and b/springdb/docs/Post/getAll.png differ diff --git a/springdb/docs/Post/getOne.png b/springdb/docs/Post/getOne.png new file mode 100644 index 0000000..da319dc Binary files /dev/null and b/springdb/docs/Post/getOne.png differ diff --git a/springdb/docs/Post/newPost.png b/springdb/docs/Post/newPost.png new file mode 100644 index 0000000..e1079d2 Binary files /dev/null and b/springdb/docs/Post/newPost.png differ diff --git a/springdb/docs/Post/updatePost.png b/springdb/docs/Post/updatePost.png new file mode 100644 index 0000000..a8bb5d9 Binary files /dev/null and b/springdb/docs/Post/updatePost.png differ diff --git a/springdb/docs/notFound404.png b/springdb/docs/notFound404.png new file mode 100644 index 0000000..b7591a1 Binary files /dev/null and b/springdb/docs/notFound404.png differ diff --git a/springdb/gradle/wrapper/gradle-wrapper.jar b/springdb/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc Binary files /dev/null and b/springdb/gradle/wrapper/gradle-wrapper.jar differ diff --git a/springdb/gradle/wrapper/gradle-wrapper.properties b/springdb/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c61a118 --- /dev/null +++ b/springdb/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/springdb/gradlew b/springdb/gradlew new file mode 100644 index 0000000..739907d --- /dev/null +++ b/springdb/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/springdb/gradlew.bat b/springdb/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/springdb/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/springdb/settings.gradle b/springdb/settings.gradle new file mode 100644 index 0000000..c0a52b7 --- /dev/null +++ b/springdb/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'springdb' diff --git a/springdb/src/main/java/com/board/springdb/SpringdbApplication.java b/springdb/src/main/java/com/board/springdb/SpringdbApplication.java new file mode 100644 index 0000000..79718ac --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/SpringdbApplication.java @@ -0,0 +1,15 @@ +package com.board.springdb; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +@EnableJpaAuditing +public class SpringdbApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringdbApplication.class, args); + } + +} diff --git a/springdb/src/main/java/com/board/springdb/comment/controller/CommentController.java b/springdb/src/main/java/com/board/springdb/comment/controller/CommentController.java new file mode 100644 index 0000000..5df5cb6 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/comment/controller/CommentController.java @@ -0,0 +1,70 @@ +package com.board.springdb.comment.controller; + +import com.board.springdb.comment.dto.CommentRequest; +import com.board.springdb.comment.dto.CommentResponse; +import com.board.springdb.comment.service.CommentService; +import com.board.springdb.global.rsdata.RsData; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Slice; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/post") +@RequiredArgsConstructor +public class CommentController { + private final CommentService commentService; + + + // 댓글 생성 + @PostMapping("/{id}/comment") + public ResponseEntity> newComment(@RequestBody CommentRequest commentRequest, @PathVariable Long id) { + CommentResponse commentResponse = commentService.newComment(id, commentRequest); + RsData rsData = new RsData<>("201-1", "댓글이 등록되었습니다", commentResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + //댓글 단건 조회 + @GetMapping("/{id}/comment/{commentId}") + public ResponseEntity> oneComment(@PathVariable Long id, @PathVariable Long commentId) { + CommentResponse commentResponse = commentService.findOneComment(id,commentId); + RsData rsData = new RsData<>("200-1", "해당 댓글 조회 완료되었습니다", commentResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + //댓글 수정 + @PutMapping("/{id}/comment/{commentId}") + public ResponseEntity> updateCommet(@PathVariable Long id, @PathVariable Long commentId,@RequestBody CommentRequest request){ + CommentResponse commentResponse = commentService.updateComment(id,commentId,request); + RsData rsData = new RsData<>("200-1","댓글이 수정되었습니다",commentResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + // 댓글 전체 조회하기(slice) + @GetMapping("/{id}/comment") + public ResponseEntity>> getComment( + @PathVariable Long id, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int size) { + Slice commentResponses = commentService.getCommentWithSlice(id, page, size); + RsData> rsData = new RsData<>("200-1", "댓글 조회가 완료되었습니다", commentResponses); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + @DeleteMapping("/{id}/comment/{commentId}") + public ResponseEntity> deleteComment(@PathVariable Long id, @PathVariable Long commentId){ + commentService.deleteComment(id, commentId); + + RsData rsData = new RsData<>("200-1", "댓글이 정상적으로 삭제 되었습니다"); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + + + + + + + + +} diff --git a/springdb/src/main/java/com/board/springdb/comment/dto/CommentRequest.java b/springdb/src/main/java/com/board/springdb/comment/dto/CommentRequest.java new file mode 100644 index 0000000..d3361af --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/comment/dto/CommentRequest.java @@ -0,0 +1,7 @@ +package com.board.springdb.comment.dto; + +public record CommentRequest( + String commentUserName, // 작성자 이름 + String commentContent +) { +} \ No newline at end of file diff --git a/springdb/src/main/java/com/board/springdb/comment/dto/CommentResponse.java b/springdb/src/main/java/com/board/springdb/comment/dto/CommentResponse.java new file mode 100644 index 0000000..10330a8 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/comment/dto/CommentResponse.java @@ -0,0 +1,17 @@ +package com.board.springdb.comment.dto; + + +import lombok.Builder; + +import java.time.LocalDateTime; + +@Builder +public record CommentResponse( + Long commentId, + String commentUserName, // 작성자 이름 + String commentContent, + Long boardId, + LocalDateTime createAt + +) { +} \ No newline at end of file diff --git a/springdb/src/main/java/com/board/springdb/comment/entity/Comment.java b/springdb/src/main/java/com/board/springdb/comment/entity/Comment.java new file mode 100644 index 0000000..915ff25 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/comment/entity/Comment.java @@ -0,0 +1,48 @@ +package com.board.springdb.comment.entity; + + +import com.board.springdb.global.BaseTimeEntity; +import com.board.springdb.post.entity.Post; +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +@Table(name = "Comment") +public class Comment extends BaseTimeEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "comment_id") + private Long comment_Id; + + @Column(name = "userId", nullable = false) + String commentUserName; + + @Column(name = "content", nullable = false) + String commentContent; + + @JoinColumn(name = "board_id") + @ManyToOne(fetch = FetchType.LAZY) + private Post post; + + + @Builder + public Comment(String commentContent,String commentUserName,Post post){ + this.commentContent =commentContent; + this.commentUserName = commentUserName; + this.post =post; + } + + public void update(String commentContent){ + this.commentContent =commentContent; + } + + + + +} diff --git a/springdb/src/main/java/com/board/springdb/comment/repository/CommentRepository.java b/springdb/src/main/java/com/board/springdb/comment/repository/CommentRepository.java new file mode 100644 index 0000000..a8d0b67 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/comment/repository/CommentRepository.java @@ -0,0 +1,10 @@ +package com.board.springdb.comment.repository; + +import com.board.springdb.comment.entity.Comment; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CommentRepository extends JpaRepository { + Slice findByPostId(Long Id, Pageable pageable); +} diff --git a/springdb/src/main/java/com/board/springdb/comment/service/CommentService.java b/springdb/src/main/java/com/board/springdb/comment/service/CommentService.java new file mode 100644 index 0000000..03db56e --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/comment/service/CommentService.java @@ -0,0 +1,116 @@ +package com.board.springdb.comment.service; + +import com.board.springdb.comment.dto.CommentRequest; +import com.board.springdb.comment.dto.CommentResponse; +import com.board.springdb.comment.entity.Comment; +import com.board.springdb.comment.repository.CommentRepository; +import com.board.springdb.post.dto.PostResponse; +import com.board.springdb.post.entity.Post; +import com.board.springdb.post.repository.PostRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class CommentService { + private final CommentRepository commentRepository; + private final PostRepository postRepository; + + + //댓글 생성 + @Transactional + public CommentResponse newComment(Long board_id, CommentRequest request){ + Post post = postRepository.findById(board_id).orElseThrow(IllegalArgumentException::new); + + Comment comment = Comment.builder(). + commentContent(request.commentContent()). + commentUserName(request.commentUserName()). + post(post). + build(); + Comment saveComment =commentRepository.save(comment); + + return CommentResponse.builder(). + commentId(saveComment.getComment_Id()). + commentContent(saveComment.getCommentContent()). + commentUserName(saveComment.getCommentUserName()). + boardId(comment.getPost().getId()).createAt(comment.getCreateAt()).build(); + + + } + + // 댓글 수정 + @Transactional + public CommentResponse updateComment(Long id, Long comment_id,CommentRequest request){ + Post post =postRepository.findById(id).orElseThrow(IllegalArgumentException::new); + Comment comment = commentRepository.findById(comment_id).orElseThrow(IllegalArgumentException::new); + + if(!comment.getPost().getId().equals(id)){ + throw new IllegalArgumentException(); + } + + comment.update(request.commentContent()); + return CommentResponse.builder(). + commentId(comment.getComment_Id()). + commentContent(comment.getCommentContent()). + commentUserName(comment.getCommentUserName()). + boardId(comment.getPost().getId()). + createAt(comment.getCreateAt()). + build(); + } + + // 댓글 단건 조회 + public CommentResponse findOneComment(Long id, Long comment_id){ + Post post =postRepository.findById(id).orElseThrow(IllegalArgumentException::new); + Comment comment = commentRepository.findById(comment_id).orElseThrow(IllegalArgumentException::new); + + if(!comment.getPost().getId().equals(id)){ + throw new IllegalArgumentException(); + } + + + return CommentResponse.builder(). + commentId(comment.getComment_Id()). + commentContent(comment.getCommentContent()). + commentUserName(comment.getCommentUserName()). + createAt(comment.getCreateAt()). + boardId(comment.getPost().getId()) + .build(); + } + // 댓글 전체 조회 -slice 적용 + public Slice getCommentWithSlice(Long boardId,int page, int size){ + Pageable pageable = PageRequest.of(page, size, Sort.by("createAt").descending()); + return commentRepository.findByPostId(boardId, pageable) + .map(comment -> CommentResponse.builder(). + commentId(comment.getComment_Id()). + commentContent(comment.getCommentContent()). + commentUserName(comment.getCommentUserName()). + boardId(comment.getPost().getId()). + createAt(comment.getCreateAt()) + .build()); + } + + // 댓글 삭제 + @Transactional + public void deleteComment(Long id,Long commentId){ + Post post =postRepository.findById(id).orElseThrow(IllegalArgumentException::new); + Comment comment = commentRepository.findById(commentId).orElseThrow(IllegalArgumentException::new); + if(!comment.getPost().getId().equals(id)){ + throw new IllegalArgumentException(); + } + + commentRepository.delete(comment); + } + + + + + + + +} diff --git a/springdb/src/main/java/com/board/springdb/global/BaseTimeEntity.java b/springdb/src/main/java/com/board/springdb/global/BaseTimeEntity.java new file mode 100644 index 0000000..7750102 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/global/BaseTimeEntity.java @@ -0,0 +1,18 @@ +package com.board.springdb.global; + +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public class BaseTimeEntity { + + @CreatedDate + private LocalDateTime createAt; +} diff --git a/springdb/src/main/java/com/board/springdb/global/exception/GlobalExceptionHandler.java b/springdb/src/main/java/com/board/springdb/global/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..89cddcd --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/global/exception/GlobalExceptionHandler.java @@ -0,0 +1,20 @@ +package com.board.springdb.global.exception; + +import com.board.springdb.global.rsdata.RsData; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity> handleIllegalArgumentException(IllegalArgumentException e) { + + RsData rsData = new RsData<>("404-1", "존재하지 않는 게시물입니다."); + + return ResponseEntity + .status(rsData.statusCode()) + .body(rsData); + } +} \ No newline at end of file diff --git a/springdb/src/main/java/com/board/springdb/global/rsdata/RsData.java b/springdb/src/main/java/com/board/springdb/global/rsdata/RsData.java new file mode 100644 index 0000000..a0d60e4 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/global/rsdata/RsData.java @@ -0,0 +1,14 @@ +package com.board.springdb.global.rsdata; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public record RsData(String resultCode, @JsonIgnore int statusCode, String message, T data) { + + public RsData(String resultCode, String message){ + this(resultCode,message,null); + } + + public RsData(String resultCode, String message, T data){ + this(resultCode,Integer.parseInt(resultCode.split("-", 2)[0]),message,data ); + } +} \ No newline at end of file diff --git a/springdb/src/main/java/com/board/springdb/post/controller/PostController.java b/springdb/src/main/java/com/board/springdb/post/controller/PostController.java new file mode 100644 index 0000000..efcba80 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/post/controller/PostController.java @@ -0,0 +1,71 @@ +package com.board.springdb.post.controller; + +import com.board.springdb.global.rsdata.RsData; +import com.board.springdb.post.dto.PostNewRequest; +import com.board.springdb.post.dto.PostResponse; +import com.board.springdb.post.dto.PostUpdateRequest; +import com.board.springdb.post.service.PostService; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + + +@RestController +@RequestMapping("/post") +@RequiredArgsConstructor +public class PostController { + private final PostService postService; + + // 게시물 등록 + @PostMapping + public ResponseEntity> newPost(@Valid @RequestBody PostNewRequest requestDto){ + PostResponse postResponse = postService.newPost(requestDto); + RsData rsData = new RsData<>("201-1","게시물이 등록되었습니다",postResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + // 게시물 전체 조회 + /*@GetMapping + public ResponseEntity>> allPost(){ + List allPost = postService.findAllPost(); + RsData> rsData = new RsData<>("200-1","전체 게시물 조회가 완료되었습니다",allPost); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + }*/ + + // 게시물 단건 조회 + @GetMapping("/{id}") + public ResponseEntity> onePost(@PathVariable Long id){ + PostResponse postResponse = postService.findOnePost(id); + RsData rsData = new RsData<>("200-2","한개의 게시물 조회가 완료되었습니다",postResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + //게시물 수정 + @PutMapping("/{id}") + public ResponseEntity> updatePost(@PathVariable Long id, @RequestBody PostUpdateRequest requestDto){ + PostResponse postResponse = postService.updatePost(requestDto,id); + RsData rsData = new RsData<>("200-3","게시물이 정상적으로 수정되었습니다",postResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + // 게시물 삭제 + @DeleteMapping("/{id}") + public ResponseEntity> deletePost(@PathVariable Long id ){ + postService.deletePost(id); + + RsData rsData = new RsData<>("200-4", "게시물이 정상적으로 삭제되었습니다"); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + // 전체 조회하기 (페이징) + @GetMapping + public ResponseEntity>> getPost( + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int size) { + Page postResponse = postService.getPostWithPaging(page, size); + RsData> rsData = new RsData<>("200-5", (page + 1)+"페이지 조회가 완료되었습니다", postResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + +} diff --git a/springdb/src/main/java/com/board/springdb/post/dto/PostNewRequest.java b/springdb/src/main/java/com/board/springdb/post/dto/PostNewRequest.java new file mode 100644 index 0000000..d197f1f --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/post/dto/PostNewRequest.java @@ -0,0 +1,15 @@ +package com.board.springdb.post.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + + + +public record PostNewRequest( + @Size(max = 200, message = "200자 까지만 가능합니다") + String title, + @Size(max = 500, message = "500자 까지만 가능합니다") + String content, + String userName +) { +} diff --git a/springdb/src/main/java/com/board/springdb/post/dto/PostResponse.java b/springdb/src/main/java/com/board/springdb/post/dto/PostResponse.java new file mode 100644 index 0000000..69a995b --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/post/dto/PostResponse.java @@ -0,0 +1,10 @@ +package com.board.springdb.post.dto; + + +import lombok.Builder; + +import java.time.LocalDateTime; + +@Builder + public record PostResponse(Long id , String title, String content, String userName, LocalDateTime createAt){} + diff --git a/springdb/src/main/java/com/board/springdb/post/dto/PostUpdateRequest.java b/springdb/src/main/java/com/board/springdb/post/dto/PostUpdateRequest.java new file mode 100644 index 0000000..ebda558 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/post/dto/PostUpdateRequest.java @@ -0,0 +1,7 @@ +package com.board.springdb.post.dto; + +public record PostUpdateRequest( + String title, + String content +) { +} diff --git a/springdb/src/main/java/com/board/springdb/post/entity/Post.java b/springdb/src/main/java/com/board/springdb/post/entity/Post.java new file mode 100644 index 0000000..cd94a0d --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/post/entity/Post.java @@ -0,0 +1,57 @@ +package com.board.springdb.post.entity; + +import com.board.springdb.comment.entity.Comment; +import com.board.springdb.global.BaseTimeEntity; +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Table(name = "board") +public class Post extends BaseTimeEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "board_id") + private Long id; + + @Column(name = "title" ,length = 200, nullable = false) + private String title; + + @Column(name = "content",length = 500, nullable = false) + private String content; + + @Column(name = "userName",nullable = false) + private String userName; + + + @OneToMany(mappedBy = "post") + List comments = new ArrayList<>(); + + @Builder + public Post (String title, String content, String userName){ + this.title= title; + this.content = content; + this. userName = userName; + } + + public void update(String title, String content){ + this.title = title; + this.content = content; + } + + + + + + + + + +} diff --git a/springdb/src/main/java/com/board/springdb/post/repository/PostRepository.java b/springdb/src/main/java/com/board/springdb/post/repository/PostRepository.java new file mode 100644 index 0000000..12f0fbd --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/post/repository/PostRepository.java @@ -0,0 +1,17 @@ +package com.board.springdb.post.repository; + +import com.board.springdb.post.entity.Post; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface PostRepository extends JpaRepository { + @Override + Page findAll(Pageable pageable); + + +} diff --git a/springdb/src/main/java/com/board/springdb/post/service/PostService.java b/springdb/src/main/java/com/board/springdb/post/service/PostService.java new file mode 100644 index 0000000..5582011 --- /dev/null +++ b/springdb/src/main/java/com/board/springdb/post/service/PostService.java @@ -0,0 +1,110 @@ +package com.board.springdb.post.service; + +import com.board.springdb.post.dto.PostNewRequest; +import com.board.springdb.post.dto.PostResponse; +import com.board.springdb.post.dto.PostUpdateRequest; +import com.board.springdb.post.entity.Post; +import com.board.springdb.post.repository.PostRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; + +@Transactional(readOnly = true) +@Service +@RequiredArgsConstructor +public class PostService { + private final PostRepository postRepository; + + // 게시물 생성 + @Transactional + public PostResponse newPost(PostNewRequest request){ + Post post = Post.builder(). + title(request.title()). + content(request.content()). + userName(request.userName()).build(); + Post savePost = postRepository.save(post); + + return PostResponse.builder(). + id(savePost.getId()). + title(savePost.getTitle()). + content(savePost.getContent()). + userName(savePost.getUserName()). + createAt(savePost.getCreateAt()) + .build(); + } + + // 게시물 갱신 + @Transactional + public PostResponse updatePost(PostUpdateRequest request, Long id) { + Post post = postRepository.findById(id).orElseThrow(IllegalArgumentException::new); + post.update(request.title(), request.content()); + return PostResponse.builder(). + id(post.getId()). + title(post.getTitle()). + content(post.getContent()). + userName(post.getUserName()). + createAt(post.getCreateAt()). + build(); + + + } + + /*// 전체 조회 + public List findAllPost() { + List posts = postRepository.findAll(); + List result = new ArrayList<>(); + + for (Post post : posts) { + PostResponse response = PostResponse.builder(). + id(post.getId()). + title(post.getTitle()). + content(post.getContent()). + userName(post.getUserName()). + createAt(post.getCreateAt()). + build(); + result.add(response); + } + return result; + }*/ + + // 단건 조회 + public PostResponse findOnePost(Long id){ + Post post = postRepository.findById(id).orElseThrow(IllegalArgumentException::new); + return PostResponse.builder(). + id(post.getId()) + .title(post.getTitle()). + content(post.getContent()). + userName(post.getUserName()). + createAt(post.getCreateAt()). + build(); + + } + + // 단건 삭제 + @Transactional + public void deletePost(Long id){ + Post post = postRepository.findById(id).orElseThrow(IllegalArgumentException::new); + postRepository.delete(post); + } + + //페이지 전체 조회 + public Page getPostWithPaging(int page, int size){ + Pageable pageable = PageRequest.of(page, size, Sort.by("createAt").descending()); + return postRepository.findAll(pageable) + .map(post -> PostResponse.builder() + .id(post.getId()) + .title(post.getTitle()) + .content(post.getContent()) + .userName(post.getUserName()) + .createAt(post.getCreateAt()) + .build() ); + } + +} diff --git a/springdb/src/main/resources/application.properties b/springdb/src/main/resources/application.properties new file mode 100644 index 0000000..ca95765 --- /dev/null +++ b/springdb/src/main/resources/application.properties @@ -0,0 +1,16 @@ + +spring.application.name=springdb +spring.config.import=optional:file:.env[.properties] + +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.datasource.url=${DB_URL} +spring.datasource.username=${DB_USERNAME} +spring.datasource.password=${DB_PASSWORD} + +spring.thymeleaf.cache=false + +spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect +spring.jpa.open-in-view=false +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto=update diff --git a/springdb/src/test/java/com/board/springdb/SpringdbApplicationTests.java b/springdb/src/test/java/com/board/springdb/SpringdbApplicationTests.java new file mode 100644 index 0000000..86c6941 --- /dev/null +++ b/springdb/src/test/java/com/board/springdb/SpringdbApplicationTests.java @@ -0,0 +1,13 @@ +package com.board.springdb; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringdbApplicationTests { + + @Test + void contextLoads() { + } + +}