diff --git a/.env b/.env new file mode 100644 index 000000000..7df74f7f8 --- /dev/null +++ b/.env @@ -0,0 +1,9 @@ +# Spring Boot 애플리케이션을 위한 환경 속성. +# host:port 형식의 호스트 URL + DB_HOST=localhost:3306 +# 데이터베이스. +DB_DATABASE=library +# 데이터베이스의 사용자 이름. +DB_USER=library +# 데이터베이스의 비밀번호. +DB_PASS=library \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..fcd388998 --- /dev/null +++ b/.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/ +!.idea/codeStyles/ +!.idea/runConfigurations/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 000000000..155ea5478 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,583 @@ + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 000000000..79ee123c2 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/LibraryApplication.xml b/.idea/runConfigurations/LibraryApplication.xml new file mode 100644 index 000000000..556058b7e --- /dev/null +++ b/.idea/runConfigurations/LibraryApplication.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index cf5104cc0..000000000 --- a/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# [프로젝트] React - Spring Boot 상품 관리, 주문관리 API 구현 -## 프로젝트 소개 😎 -React로 만들어진 Front End가 정해져있는 상황에서, -백엔드 개발자가 Spring Boot로 상품관리 API를 구현하여 A-Z 최종 서비스를 완성시켜봅니다. -클로닝 외에도 "본인만의 아이디어"를 추가하여 더 발전시켜 완성해봅니다. - -## 이곳은 공개 Repo입니다. -1. 이 repo를 fork한 뒤 -2. 여러분의 개인 Repo에서 상품관리 API를 A-Z까지 작업하여 -3. 개발이 끝나면 이 Repo에 PR을 보내어 제출을 완료해주세요. diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..c2ecb5ba4 --- /dev/null +++ b/build.gradle @@ -0,0 +1,46 @@ +plugins { + id 'java' + id 'war' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' + id 'com.palantir.git-version' version '3.0.0' +} + +group = 'com.null0xff.project' +version = gitVersion() + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + developmentOnly 'org.springframework.boot:spring-boot-docker-compose' + runtimeOnly 'org.mariadb.jdbc:mariadb-java-client' + annotationProcessor 'org.projectlombok:lombok' + providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.boot:spring-boot-testcontainers' + testImplementation 'org.testcontainers:junit-jupiter' + testImplementation 'org.testcontainers:mariadb' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 000000000..12289af00 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,15 @@ +version: "3" + +services: + mariadb: + image: 'mariadb:10.6' + environment: + - 'MARIADB_ROOT_PASSWORD=' + - 'MARIADB_ALLOW_EMPTY_ROOT_PASSWORD=true' + - 'MARIADB_USER=${DB_USER}' + - 'MARIADB_PASSWORD=${DB_PASS}' + - 'MARIADB_DATABASE=${DB_DATABASE}' + ports: + - '3306:3306' + volumes: + - "./conf.d:/etc/mysql/mariadb.conf.d:ro" \ 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..033e24c4c 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..9f4197d5f --- /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.2.1-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..fcb6fca14 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/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##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && 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=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=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, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +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/sample.html b/sample.html deleted file mode 100644 index 2db14018b..000000000 --- a/sample.html +++ /dev/null @@ -1,149 +0,0 @@ - - - - - - - - - - - Hello, world! - - -
-

Grids & Circle

-
-
-
-
-
상품 목록
-
    -
  • -
    -
    -
    커피콩
    -
    Columbia Nariñó
    -
    -
    5000원
    - -
  • -
  • -
    -
    -
    커피콩
    -
    Columbia Nariñó
    -
    -
    5000원
    - -
  • -
  • -
    -
    -
    커피콩
    -
    Columbia Nariñó
    -
    -
    5000원
    - -
  • -
-
-
-
-
Summary
-
-
-
-
Columbia Nariñó 2개
-
-
-
Brazil Serra Do Caparaó 2개
-
-
-
Columbia Nariñó 2개
-
-
-
- - -
-
- - -
-
- - -
-
당일 오후 2시 이후의 주문은 다음날 배송을 시작합니다.
-
-
-
총금액
-
15000원
-
- -
-
-
- - \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..835224aef --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'library' diff --git a/src/main/java/com/null0xff/project/library/LibraryApplication.java b/src/main/java/com/null0xff/project/library/LibraryApplication.java new file mode 100644 index 000000000..f23b6b77f --- /dev/null +++ b/src/main/java/com/null0xff/project/library/LibraryApplication.java @@ -0,0 +1,36 @@ +package com.null0xff.project.library; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * LibraryApplication은 'library' SpringBoot 프로젝트의 시작점 역할을 합니다. + *

+ * 이 클래스는 SpringBoot 애플리케이션을 부트스트랩하고 내장 웹 서버를 시작하여 'library' 프로젝트의 서비스와 기능을 활용할 수 있게 합니다. main 메소드는 + * {@link LibraryApplication}을 주요 구성 클래스로 사용하여 SpringBoot 애플리케이션을 호출합니다. + *

+ * + *

사용법

+ *
+ * java -jar library-0.0.1-SNAPSHOT.jar
+ * 
+ *

+ * 시작한 후 애플리케이션의 서비스는 'library.project.null0xff.com'을 통해 접근 가능합니다. + * + * @author Ji Myoung Ha + * @version 1.0 + * @see library.project.null0xff.com + * @since 2023-10-25 + */ +@SpringBootApplication +public class LibraryApplication { + + /** + * SpringBoot 애플리케이션의 시작점 역할을 하는 main 메소드. + * + * @param args 애플리케이션에 전달된 명령 줄 인수. + */ + public static void main(String[] args) { + SpringApplication.run(LibraryApplication.class, args); + } +} diff --git a/src/main/java/com/null0xff/project/library/ServletInitializer.java b/src/main/java/com/null0xff/project/library/ServletInitializer.java new file mode 100644 index 000000000..01fdc6665 --- /dev/null +++ b/src/main/java/com/null0xff/project/library/ServletInitializer.java @@ -0,0 +1,35 @@ +package com.null0xff.project.library; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +/** + * 서블릿 컨테이너에서 전통적인 WAR로 애플리케이션을 배포하기 위한 서블릿 초기화 클래스입니다. + *

+ * 이 클래스는 {@code SpringBootServletInitializer}를 확장하여 서블릿 컨테이너에서 애플리케이션을 시작할 수 있게 해주며, 프로그래밍 방식으로 서블릿 + * 컨텍스트를 구성합니다. 이 구성에서는 {@code LibraryApplication}이 주요 Spring Boot 애플리케이션 클래스로 지정됩니다. + *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @see com.null0xff.project.library.LibraryApplication + * @see org.springframework.boot.web.servlet.support.SpringBootServletInitializer + * @since 2023-10-25 + */ +public class ServletInitializer extends SpringBootServletInitializer { + + /** + * 애플리케이션을 구성합니다. + *

+ * 이 메소드는 서블릿 컨텍스트 초기화를 위한 주요 Spring Boot 애플리케이션 클래스를 가리킵니다. + *

+ * + * @param application 스프링 애플리케이션 빌더입니다. + * @return 구성된 애플리케이션 빌더를 반환합니다. + */ + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(LibraryApplication.class); + } + +} diff --git a/src/main/java/com/null0xff/project/library/controller/LibraryRestController.java b/src/main/java/com/null0xff/project/library/controller/LibraryRestController.java new file mode 100644 index 000000000..86ac2f0c5 --- /dev/null +++ b/src/main/java/com/null0xff/project/library/controller/LibraryRestController.java @@ -0,0 +1,84 @@ +package com.null0xff.project.library.controller; + +import com.null0xff.project.library.dto.BookForm; +import com.null0xff.project.library.model.Book; +import com.null0xff.project.library.service.LibraryService; +import java.util.List; +import java.util.UUID; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * LibraryRestController 클래스는 모든 책을 나열하고 특정 책의 세부 정보를 검색하는 것과 같은 도서관 관련 작업을 위한 RESTful API를 제공합니다. + *

+ * 주요 엔드포인트 접두사는 "/api/v1/library"입니다. + *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @since 2023-10-25 + */ +@RestController +@RequestMapping(value = "/api/v1/library") +public class LibraryRestController { + + private final LibraryService libraryService; + + /** + * LibraryRestController의 새로운 인스턴스를 구성합니다. + * + * @param libraryService 도서관 데이터와 상호 작용하기 위한 {@link LibraryService}의 인스턴스. + */ + public LibraryRestController(LibraryService libraryService) { + this.libraryService = libraryService; + } + + /** + * 도서관에서 사용 가능한 모든 책의 목록을 검색합니다. + * + * @return {@link Book} 객체의 목록. + */ + @RequestMapping(value = "/books") + public List listBooks() { + return libraryService.listAll(); + } + + /** + * 식별자로 특정 책의 세부 정보를 검색합니다. + * + * @param id 책의 식별자. + * @return 책 세부 정보를 나타내는 {@link Book} 객체. + */ + @RequestMapping(value = "/book/{id}") + public Book getBook(@PathVariable String id) { + return libraryService.getById(UUID.fromString(id)); + } + + /** + * 도서관에 새로운 책을 등록합니다. + * + * @param request 새로운 책의 세부 정보를 포함하는 {@link BookForm} 객체. + * @return 작업의 성공 또는 실패를 나타내는 {@link ResponseEntity} 객체. + */ + @RequestMapping(value = "/book") + public Book newBook(@RequestBody BookForm request) { + return libraryService.saveOrUpdateBookForm(request); + } + + /** + * 식별자를 사용하여 도서관에서 책을 삭제합니다. + * + * @param id 삭제할 책의 식별자. + * @return 작업의 성공 또는 실패를 나타내는 {@link ResponseEntity} 객체. + */ + @DeleteMapping(value = "/book/{id}") + public ResponseEntity delete(@PathVariable String id) { + libraryService.delete(UUID.fromString(id)); + return ResponseEntity.ok().build(); + } + +} diff --git a/src/main/java/com/null0xff/project/library/converter/BookFormToBook.java b/src/main/java/com/null0xff/project/library/converter/BookFormToBook.java new file mode 100644 index 000000000..f4806294c --- /dev/null +++ b/src/main/java/com/null0xff/project/library/converter/BookFormToBook.java @@ -0,0 +1,40 @@ +package com.null0xff.project.library.converter; + +import com.null0xff.project.library.dto.BookForm; +import com.null0xff.project.library.model.Book; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +/** + * {@code BookForm} DTO를 {@code Book} 엔터티 객체로 변환하는 컨버터. + *

+ * 이 클래스는 {@code BookForm} DTO 객체의 데이터를 {@code Book} 엔터티 객체로 변환하는데 사용됩니다. Spring의 {@code Converter} + * 인터페이스를 구현하여 변환 로직을 제공합니다. + *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @see com.null0xff.project.library.dto.BookForm + * @see com.null0xff.project.library.model.Book + * @since 2023-10-25 + */ +@Component +public class BookFormToBook implements Converter { + + /** + * 주어진 {@code BookForm} 객체를 {@code Book} 엔터티로 변환합니다. + * + * @param sourceBook 변환될 {@code BookForm} 객체. + * @return 변환된 {@code Book} 엔터티. + */ + @Override + public Book convert(BookForm sourceBook) { + Book book = new Book(); + if (sourceBook.id() != null) { + book.setId(sourceBook.id()); + } + book.setTitle(sourceBook.title()); + return book; + } + +} diff --git a/src/main/java/com/null0xff/project/library/dto/BookForm.java b/src/main/java/com/null0xff/project/library/dto/BookForm.java new file mode 100644 index 000000000..e58d43187 --- /dev/null +++ b/src/main/java/com/null0xff/project/library/dto/BookForm.java @@ -0,0 +1,17 @@ +package com.null0xff.project.library.dto; + +import java.util.UUID; + +/** + * 도서의 양식 상세를 나타내는 레코드입니다. + *

+ * 이 레코드는 주로 도서 생성 중 클라이언트로부터 정보를 수집하기 위해 사용됩니다. + *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @since 2023-10-25 + */ +public record BookForm(UUID id, String title) { + +} diff --git a/src/main/java/com/null0xff/project/library/model/BaseEntity.java b/src/main/java/com/null0xff/project/library/model/BaseEntity.java new file mode 100644 index 000000000..3e916d997 --- /dev/null +++ b/src/main/java/com/null0xff/project/library/model/BaseEntity.java @@ -0,0 +1,36 @@ +package com.null0xff.project.library.model; + +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; +import java.io.Serializable; +import java.util.UUID; +import lombok.Data; + +/** + * 라이브러리 애플리케이션의 기본 엔터티를 나타냅니다. + *

+ * 이 클래스는 유니버설 유니크 식별자(UUID)가 필요한 라이브러리 애플리케이션의 모든 엔터티 모델의 슈퍼클래스로서의 역할을 합니다. 다양한 엔터티 간에 공유되는 공통 속성과 + * 동작을 캡슐화합니다. + *

+ *

+ * {@code MappedSuperclass} 주석은 이 클래스의 속성이 엔터티 서브클래스의 데이터베이스 테이블에 매핑된다는 것을 나타냅니다. + *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @since 2023-10-25 + */ +@Data +@MappedSuperclass +public class BaseEntity implements Serializable { + + /** + * 엔터티를 위한 유니버설 유니크 식별자입니다. + */ + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + +} diff --git a/src/main/java/com/null0xff/project/library/model/Book.java b/src/main/java/com/null0xff/project/library/model/Book.java new file mode 100644 index 000000000..9dd43233b --- /dev/null +++ b/src/main/java/com/null0xff/project/library/model/Book.java @@ -0,0 +1,35 @@ +package com.null0xff.project.library.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import lombok.Getter; +import lombok.Setter; + +/** + * 라이브러리 애플리케이션에서 책 엔터티를 나타냅니다. + *

+ * 이 클래스는 라이브러리의 책에 특정한 속성과 동작을 캡슐화합니다. {@code Book} 엔터티는 {@code BaseEntity}를 확장하며, 주 키로서의 유니버설 유니크 + * 식별자(UUID)를 상속받습니다. + *

+ *

+ * {@code Entity} 주석은 이 클래스가 JPA 엔터티임을 나타내며, {@code Table} 주석은 엔터티와 연관된 데이터베이스 테이블 이름을 지정합니다. + *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @since 2023-10-25 + */ +@Getter +@Setter +@Entity +@Table(name = "books") +public class Book extends BaseEntity { + + /** + * 책의 제목입니다. + */ + @Column(name = "title") + private String title; + +} diff --git a/src/main/java/com/null0xff/project/library/repository/BookRepository.java b/src/main/java/com/null0xff/project/library/repository/BookRepository.java new file mode 100644 index 000000000..23141a74b --- /dev/null +++ b/src/main/java/com/null0xff/project/library/repository/BookRepository.java @@ -0,0 +1,27 @@ +package com.null0xff.project.library.repository; + +import com.null0xff.project.library.model.Book; +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * {@code Book} 엔터티에 대한 CRUD 작업을 위한 리포지토리 인터페이스. + *

+ * 이 인터페이스는 Spring Data JPA가 제공하는 {@code JpaRepository} 인터페이스를 확장하며, {@code Book} 엔터티에 대한 CRUD 및 + * 페이지네이션 기능을 활용합니다. 주 키의 데이터 타입으로 UUID를 사용합니다. + *

+ *

+ * {@code Repository} 주석은 이것이 Spring Data 리포지토리라는 것을 나타냅니다. 스프링은 자동으로 이 리포지토리 인터페이스의 구체적인 구현을 생성하며, + * 일반적인 CRUD 작업에 대한 메서드를 제공합니다. + *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @see com.null0xff.project.library.model.Book + * @since 2023-10-25 + */ +@Repository +public interface BookRepository extends JpaRepository { + +} diff --git a/src/main/java/com/null0xff/project/library/service/DefaultLibraryService.java b/src/main/java/com/null0xff/project/library/service/DefaultLibraryService.java new file mode 100644 index 000000000..7b70cb8ed --- /dev/null +++ b/src/main/java/com/null0xff/project/library/service/DefaultLibraryService.java @@ -0,0 +1,84 @@ +package com.null0xff.project.library.service; + +import com.null0xff.project.library.converter.BookFormToBook; +import com.null0xff.project.library.dto.BookForm; +import com.null0xff.project.library.model.Book; +import com.null0xff.project.library.repository.BookRepository; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.springframework.stereotype.Service; + +/** + * {@code LibraryService} 인터페이스의 기본 구현. + *

+ * 이 서비스는 {@code Book} 엔터티에 대한 CRUD 작업의 핵심 비즈니스 로직을 제공하며, 데이터 액세스를 위해 {@code BookRepository}를 활용합니다. + * 또한, {@code BookForm}을 {@code Book} 객체로 변환하기 위해 {@code BookFormToBook} 변환기를 사용합니다. + *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @see com.null0xff.project.library.model.Book + * @see com.null0xff.project.library.repository.BookRepository + * @see com.null0xff.project.library.service.LibraryService + * @see com.null0xff.project.library.converter.BookFormToBook + * @since 2023-10-25 + */ +@Service +public class DefaultLibraryService implements LibraryService { + + private final BookRepository bookRepository; + private final BookFormToBook bookFormToBook; + + /** + * 지정된 도서 리포지토리와 도서 폼 변환기로 새로운 {@code DefaultLibraryService}를 구성합니다. + * + * @param bookRepository {@code Book} 데이터 액세스를 관리하는 리포지토리. + * @param bookFormToBook {@code BookForm}을 {@code Book} 엔터티로 변환하는데 사용하는 변환기. + */ + public DefaultLibraryService(BookRepository bookRepository, BookFormToBook bookFormToBook) { + this.bookRepository = bookRepository; + this.bookFormToBook = bookFormToBook; + } + + /** + * {@inheritDoc} + */ + @Override + public List listAll() { + return new ArrayList<>(bookRepository.findAll()); + } + + /** + * {@inheritDoc} + */ + @Override + public Book getById(UUID id) { + return bookRepository.findById(id).orElse(null); + } + + /** + * {@inheritDoc} + */ + @Override + public Book saveOrUpdate(Book book) { + return bookRepository.save(book); + } + + /** + * {@inheritDoc} + */ + @Override + public void delete(UUID id) { + bookRepository.deleteById(id); + } + + /** + * {@inheritDoc} + */ + @Override + public Book saveOrUpdateBookForm(BookForm bookForm) { + return saveOrUpdate(bookFormToBook.convert(bookForm)); + } + +} diff --git a/src/main/java/com/null0xff/project/library/service/LibraryService.java b/src/main/java/com/null0xff/project/library/service/LibraryService.java new file mode 100644 index 000000000..7f730cc56 --- /dev/null +++ b/src/main/java/com/null0xff/project/library/service/LibraryService.java @@ -0,0 +1,72 @@ +package com.null0xff.project.library.service; + +import com.null0xff.project.library.dto.BookForm; +import com.null0xff.project.library.model.Book; +import java.util.List; +import java.util.UUID; + +/** + * 도서관의 도서를 관리하기 위한 작업을 정의하는 서비스 인터페이스. + *

+ * 이 서비스는 {@code Book} 엔터티에 대한 CRUD (생성, 읽기, 업데이트, 삭제) 작업을 제공합니다. 컨트롤러와 데이터 액세스 계층 사이의 추상화 계층으로 작동하여 + * 비즈니스 로직이 데이터 처리로부터 분리되도록 합니다. + *

+ *

+ * 제공된 작업 중에는 다음과 같은 것들이 있습니다: + *

    + *
  • 모든 도서 목록화
  • + *
  • 고유 식별자로 도서 가져오기
  • + *
  • 도서 저장 또는 업데이트
  • + *
  • 고유 식별자로 도서 삭제
  • + *
+ *

+ * + * @author Ji Myoung Ha + * @version 1.0 + * @see com.null0xff.project.library.model.Book + * @since 2023-10-25 + */ +public interface LibraryService { + + /** + * 도서관의 모든 도서 목록을 검색합니다. + * + * @return 모든 {@code Book} 엔터티의 목록. + */ + List listAll(); + + /** + * 고유 식별자로 도서를 검색합니다. + * + * @param id 검색할 도서의 UUID. + * @return 지정된 UUID를 가진 {@code Book} 엔터티. + */ + Book getById(UUID id); + + /** + * 새 도서를 저장하거나 기존 도서를 업데이트합니다. + * + * @param book 저장 또는 업데이트할 {@code Book} 엔터티. + * @return 저장 또는 업데이트된 {@code Book} 엔터티. + */ + Book saveOrUpdate(Book book); + + /** + * 고유 식별자로 도서를 삭제합니다. + * + * @param id 삭제할 도서의 UUID. + */ + void delete(UUID id); + + /** + * {@code BookForm} 객체를 사용하여 새 도서를 저장하거나 기존 도서를 업데이트합니다. + *

+ * 이 메서드는 {@code BookForm}에서 정보를 가져와 {@code Book} 엔터티를 저장 또는 업데이트하는 데 사용됩니다. + *

+ * + * @param bookForm 저장 또는 업데이트할 {@code BookForm} 객체. + * @return 저장 또는 업데이트된 {@code Book} 엔터티. + */ + Book saveOrUpdateBookForm(BookForm bookForm); + +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 000000000..53c9afcbd --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,21 @@ +spring: + jpa: + hibernate: + ddl-auto: update + open-in-view: true + show-sql: true + +management: + endpoints: + web: + exposure: + include: '*' + +logging: + level: + org: + springframework: + context: + annotation: TRACE + web: DEBUG + nodeValue: INFO \ No newline at end of file diff --git a/src/test/java/com/null0xff/project/library/LibraryApplicationTests.java b/src/test/java/com/null0xff/project/library/LibraryApplicationTests.java new file mode 100644 index 000000000..b6cc954bf --- /dev/null +++ b/src/test/java/com/null0xff/project/library/LibraryApplicationTests.java @@ -0,0 +1,13 @@ +package com.null0xff.project.library; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class LibraryApplicationTests { + + @Test + void contextLoads() { + } + +}