diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..e39fb43e3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,150 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij,macos +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij,macos + +### 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/**/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 + +### 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 + +# End of https://www.toptal.com/developers/gitignore/api/intellij,macos diff --git a/jpashop/.gitignore b/jpashop/.gitignore new file mode 100644 index 000000000..c2065bc26 --- /dev/null +++ b/jpashop/.gitignore @@ -0,0 +1,37 @@ +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/ diff --git a/jpashop/build.gradle b/jpashop/build.gradle new file mode 100644 index 000000000..0a1579e0c --- /dev/null +++ b/jpashop/build.gradle @@ -0,0 +1,30 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.2' + id 'io.spring.dependency-management' version '1.1.2' +} + +group = 'org.wonu606' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + 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' + implementation 'org.springframework.boot:spring-boot-devtools:3.1.1' + runtimeOnly 'com.h2database:h2' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/jpashop/gradle/wrapper/gradle-wrapper.jar b/jpashop/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..033e24c4c Binary files /dev/null and b/jpashop/gradle/wrapper/gradle-wrapper.jar differ diff --git a/jpashop/gradle/wrapper/gradle-wrapper.properties b/jpashop/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..9f4197d5f --- /dev/null +++ b/jpashop/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/jpashop/gradlew b/jpashop/gradlew new file mode 100755 index 000000000..fcb6fca14 --- /dev/null +++ b/jpashop/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/jpashop/gradlew.bat b/jpashop/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/jpashop/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/jpashop/settings.gradle b/jpashop/settings.gradle new file mode 100644 index 000000000..8cb5550bc --- /dev/null +++ b/jpashop/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'jpashop' diff --git a/jpashop/src/main/java/org/wonu606/jpashop/JpashopApplication.java b/jpashop/src/main/java/org/wonu606/jpashop/JpashopApplication.java new file mode 100644 index 000000000..b76d7735a --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/JpashopApplication.java @@ -0,0 +1,15 @@ +package org.wonu606.jpashop; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +@EnableJpaAuditing +public class JpashopApplication { + + public static void main(String[] args) { + SpringApplication.run(JpashopApplication.class, args); + } + +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/customer/domain/Customer.java b/jpashop/src/main/java/org/wonu606/jpashop/customer/domain/Customer.java new file mode 100644 index 000000000..ccd4c123e --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/customer/domain/Customer.java @@ -0,0 +1,45 @@ +package org.wonu606.jpashop.customer.domain; + +import static jakarta.persistence.GenerationType.IDENTITY; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; + +@Entity +public class Customer { + + @Id + @GeneratedValue(strategy = IDENTITY) + @Column(name = "customer_id") + private Long id; + + private String firstName; + private String lastName; + + protected Customer() { + } + + public Customer(String firstName, String lastName) { + this(null, firstName, lastName); + } + + public Customer(Long id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Long getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/customer/domain/CustomerRepository.java b/jpashop/src/main/java/org/wonu606/jpashop/customer/domain/CustomerRepository.java new file mode 100644 index 000000000..c346af182 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/customer/domain/CustomerRepository.java @@ -0,0 +1,7 @@ +package org.wonu606.jpashop.customer.domain; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CustomerRepository extends JpaRepository { + +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/customer/service/CustomerService.java b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/CustomerService.java new file mode 100644 index 000000000..d6ae47930 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/CustomerService.java @@ -0,0 +1,64 @@ +package org.wonu606.jpashop.customer.service; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.wonu606.jpashop.customer.domain.Customer; +import org.wonu606.jpashop.customer.domain.CustomerRepository; +import org.wonu606.jpashop.customer.service.dto.CustomerCreateData; +import org.wonu606.jpashop.customer.service.dto.CustomerResult; +import org.wonu606.jpashop.customer.service.dto.CustomerResults; +import org.wonu606.jpashop.customer.service.exception.CustomerNotFoundException; + +@Service +@Transactional(readOnly = true) +public class CustomerService { + + private final CustomerRepository repository; + + public CustomerService(CustomerRepository repository) { + this.repository = repository; + } + + @Transactional + public CustomerResult create(CustomerCreateData customerCreateData) { + Customer creatingCustomer = new Customer(customerCreateData.firstName(), + customerCreateData.lastName()); + Customer savedCustomer = repository.save(creatingCustomer); + return new CustomerResult( + savedCustomer.getId(), + savedCustomer.getFirstName(), + savedCustomer.getLastName()); + } + + public CustomerResult findById(Long id) { + Optional foundCustomer = repository.findById(id); + return foundCustomer.map(c -> + new CustomerResult( + c.getId(), + c.getFirstName(), + c.getLastName())) + .orElseThrow(CustomerNotFoundException::new); + } + + public CustomerResults findAll() { + List foundCustomers = repository.findAll(); + return new CustomerResults(foundCustomers.stream() + .map(c -> + new CustomerResult( + c.getId(), + c.getFirstName(), + c.getLastName())) + .collect(Collectors.toList())); + } + + @Transactional + public void deleteById(Long id) { + if (!repository.existsById(id)) { + throw new CustomerNotFoundException(); + } + repository.deleteById(id); + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerCreateData.java b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerCreateData.java new file mode 100644 index 000000000..7289a4dc4 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerCreateData.java @@ -0,0 +1,5 @@ +package org.wonu606.jpashop.customer.service.dto; + +public record CustomerCreateData(String firstName, String lastName) { + +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerResult.java b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerResult.java new file mode 100644 index 000000000..2e4faf986 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerResult.java @@ -0,0 +1,5 @@ +package org.wonu606.jpashop.customer.service.dto; + +public record CustomerResult(Long id, String firstName, String lastName) { + +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerResults.java b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerResults.java new file mode 100644 index 000000000..05c8e0ca6 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/dto/CustomerResults.java @@ -0,0 +1,10 @@ +package org.wonu606.jpashop.customer.service.dto; + +import java.util.List; + +public record CustomerResults(List results) { + + public CustomerResults(List results) { + this.results = List.copyOf(results); + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/customer/service/exception/CustomerNotFoundException.java b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/exception/CustomerNotFoundException.java new file mode 100644 index 000000000..a4b71fde3 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/customer/service/exception/CustomerNotFoundException.java @@ -0,0 +1,8 @@ +package org.wonu606.jpashop.customer.service.exception; + +public class CustomerNotFoundException extends RuntimeException { + + public CustomerNotFoundException() { + super(); + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/item/domain/Book.java b/jpashop/src/main/java/org/wonu606/jpashop/item/domain/Book.java new file mode 100644 index 000000000..c61543cbb --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/item/domain/Book.java @@ -0,0 +1,36 @@ +package org.wonu606.jpashop.item.domain; + +import jakarta.persistence.Entity; + +@Entity +public class Book extends Item { + + private String author; + private String isbn; + + protected Book() { + } + + public Book(Long id, Integer price, Integer stockQuantity, String author, String isbn) { + super(id, price, stockQuantity); + this.author = author; + this.isbn = isbn; + } + + public Book(Integer price, Integer stockQuantity, String author, String isbn) { + super(null, price, stockQuantity); + this.author = author; + this.isbn = isbn; + } + + @Override + public String toString() { + return "Book{" + + "author='" + author + '\'' + + ", isbn='" + isbn + '\'' + + ", id=" + id + + ", price=" + price + + ", stockQuantity=" + stockQuantity + + '}'; + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/item/domain/Item.java b/jpashop/src/main/java/org/wonu606/jpashop/item/domain/Item.java new file mode 100644 index 000000000..f9e75fbab --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/item/domain/Item.java @@ -0,0 +1,31 @@ +package org.wonu606.jpashop.item.domain; + +import static jakarta.persistence.GenerationType.IDENTITY; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; + +@Entity +public abstract class Item { + + @Id + @GeneratedValue(strategy = IDENTITY) + protected Long id; + + protected Integer price; + protected Integer stockQuantity; + + public Item() { + } + + public Item(Long id, Integer price, Integer stockQuantity) { + this.id = id; + this.price = price; + this.stockQuantity = stockQuantity; + } + + public Item(Integer price, Integer stockQuantity) { + this(null, price, stockQuantity); + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/item/domain/ItemRepository.java b/jpashop/src/main/java/org/wonu606/jpashop/item/domain/ItemRepository.java new file mode 100644 index 000000000..e5b0aa322 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/item/domain/ItemRepository.java @@ -0,0 +1,7 @@ +package org.wonu606.jpashop.item.domain; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ItemRepository extends JpaRepository { + +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/item/domain/PerformanceTicket.java b/jpashop/src/main/java/org/wonu606/jpashop/item/domain/PerformanceTicket.java new file mode 100644 index 000000000..bce9ab048 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/item/domain/PerformanceTicket.java @@ -0,0 +1,32 @@ +package org.wonu606.jpashop.item.domain; + +import jakarta.persistence.Entity; + +@Entity +public class PerformanceTicket extends Item { + + private String name; + + public PerformanceTicket() { + } + + public PerformanceTicket(Long id, Integer price, Integer stockQuantity, String name) { + super(id, price, stockQuantity); + this.name = name; + } + + public PerformanceTicket(Integer price, Integer stockQuantity, String name) { + super(null, price, stockQuantity); + this.name = name; + } + + @Override + public String toString() { + return "PerformanceTicket{" + + "name='" + name + '\'' + + ", id=" + id + + ", price=" + price + + ", stockQuantity=" + stockQuantity + + '}'; + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/order/domain/Order.java b/jpashop/src/main/java/org/wonu606/jpashop/order/domain/Order.java new file mode 100644 index 000000000..3e88bfffe --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/order/domain/Order.java @@ -0,0 +1,64 @@ +package org.wonu606.jpashop.order.domain; + +import static jakarta.persistence.GenerationType.IDENTITY; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "orders") +public class Order { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Long id; + + @Column(columnDefinition = "TIMESTAMP") + private LocalDateTime orderDateTime; + + @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) + private List orderLineItems = new ArrayList<>(); + + public Order() { + } + + public Order(Long id, LocalDateTime orderDateTime, List orderLineItems) { + this.id = id; + this.orderDateTime = orderDateTime; + this.orderLineItems.addAll(orderLineItems); + } + + public Order(LocalDateTime orderDateTime, List orderLineItems) { + this(null, orderDateTime, orderLineItems); + } + + public Long getId() { + return id; + } + + public void addOrderLineItem(OrderLineItem orderLineItem) { + orderLineItems.add(orderLineItem); + orderLineItem.changeOrder(this); + } + + public void removeOrderLineItem(OrderLineItem orderLineItem) { + orderLineItems.remove(orderLineItem); + } + + @Override + public String toString() { + return "Order{" + + "id=" + id + + ", orderDateTime=" + orderDateTime + + ", orderLineItems=" + orderLineItems + + '}'; + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/order/domain/OrderLineItem.java b/jpashop/src/main/java/org/wonu606/jpashop/order/domain/OrderLineItem.java new file mode 100644 index 000000000..a72474b48 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/order/domain/OrderLineItem.java @@ -0,0 +1,73 @@ +package org.wonu606.jpashop.order.domain; + +import static jakarta.persistence.FetchType.LAZY; +import static jakarta.persistence.GenerationType.IDENTITY; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import java.util.Objects; +import org.wonu606.jpashop.item.domain.Item; + +@Entity +public class OrderLineItem { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Long id; + + // final은 강력한 제어자 + private Integer paymentAmount; + private Integer quantity; + + @ManyToOne(fetch = LAZY) + @JoinColumn(name = "item_id", referencedColumnName = "id") + private Item item; + + @ManyToOne(fetch = LAZY) + @JoinColumn(name = "order_id", referencedColumnName = "id") + private Order order; + + public OrderLineItem(Integer paymentAmount, Integer quantity, Item item) { + this.paymentAmount = paymentAmount; + this.quantity = quantity; + this.item = item; + } + + public OrderLineItem() { + } + + public OrderLineItem(Long id, Integer paymentAmount, Integer quantity, Item item, Order order) { + this.id = id; + this.paymentAmount = paymentAmount; + this.quantity = quantity; + this.item = item; + this.order = order; + } + + public OrderLineItem(Integer paymentAmount, Integer quantity, Item item, Order order) { + this(null, paymentAmount, quantity, item, order); + } + + // setter 이름 변경 + public void changeOrder(Order order) { + if (Objects.nonNull(this.order)) { + this.order.removeOrderLineItem(this); + } + + this.order = order; + } + + @Override + public String toString() { + return "OrderLineItem{" + + "id=" + id + + ", paymentAmount=" + paymentAmount + + ", quantity=" + quantity + + ", item=" + item + + ", order.id=" + order.getId() + + '}'; + } +} diff --git a/jpashop/src/main/java/org/wonu606/jpashop/order/domain/OrderRepository.java b/jpashop/src/main/java/org/wonu606/jpashop/order/domain/OrderRepository.java new file mode 100644 index 000000000..ac4017bb8 --- /dev/null +++ b/jpashop/src/main/java/org/wonu606/jpashop/order/domain/OrderRepository.java @@ -0,0 +1,19 @@ +package org.wonu606.jpashop.order.domain; + +import java.util.List; +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.lang.NonNull; + +public interface OrderRepository extends JpaRepository { + + @Override + @NonNull + @Query("SELECT o FROM Order o JOIN FETCH o.orderLineItems ol JOIN FETCH ol.item") + List findAll(); + + @Query("SELECT o FROM Order o JOIN FETCH o.orderLineItems ol JOIN FETCH ol.item WHERE o.id = :id") + Optional findByIdWithOrderLineItemsAndItems(@Param("id") Long id); +} diff --git a/jpashop/src/main/resources/application.properties b/jpashop/src/main/resources/application.properties new file mode 100644 index 000000000..e69de29bb diff --git a/jpashop/src/main/resources/application.yml b/jpashop/src/main/resources/application.yml new file mode 100755 index 000000000..8cfeb709e --- /dev/null +++ b/jpashop/src/main/resources/application.yml @@ -0,0 +1,14 @@ +spring: + datasource: + url: jdbc:h2:tcp://localhost/~/jpashop + username: sa + password: + driver-class-name: org.h2.Driver + + jpa: + hibernate: + ddl-auto: create + properties: + hibernate: + show_sql: true + format_sql: true diff --git a/jpashop/src/test/java/org/wonu606/jpashop/JpashopApplicationTests.java b/jpashop/src/test/java/org/wonu606/jpashop/JpashopApplicationTests.java new file mode 100644 index 000000000..2da10f6bc --- /dev/null +++ b/jpashop/src/test/java/org/wonu606/jpashop/JpashopApplicationTests.java @@ -0,0 +1,13 @@ +package org.wonu606.jpashop; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class JpashopApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/jpashop/src/test/java/org/wonu606/jpashop/customer/service/CustomerServiceTest.java b/jpashop/src/test/java/org/wonu606/jpashop/customer/service/CustomerServiceTest.java new file mode 100644 index 000000000..2c6ba17d2 --- /dev/null +++ b/jpashop/src/test/java/org/wonu606/jpashop/customer/service/CustomerServiceTest.java @@ -0,0 +1,104 @@ +package org.wonu606.jpashop.customer.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.wonu606.jpashop.customer.domain.CustomerRepository; +import org.wonu606.jpashop.customer.service.dto.CustomerCreateData; +import org.wonu606.jpashop.customer.service.dto.CustomerResult; +import org.wonu606.jpashop.customer.service.dto.CustomerResults; +import org.wonu606.jpashop.customer.service.exception.CustomerNotFoundException; + +@DataJpaTest +class CustomerServiceTest { + + @Autowired + private CustomerRepository repository; + private CustomerService service; + + + @BeforeEach + void setup() { + service = new CustomerService(repository); + } + + @Test + void create_유효한데이터인경우_저장된고객정보반환() { + // Given + CustomerCreateData creatingData = new CustomerCreateData("FirstName", "LastName"); + + // When + CustomerResult createdResult = service.create(creatingData); + + // Then + assertThat(createdResult.id()).isNotNull(); + assertThat(createdResult) + .usingRecursiveComparison() + .ignoringFields("id") + .isEqualTo(creatingData); + } + + @Test + void findById_존재하는아이디인경우_고객정보반환() { + // Given + CustomerCreateData creatingData = new CustomerCreateData("FirstName", "LastName"); + CustomerResult createdResult = service.create(creatingData); + + Long existingId = createdResult.id(); + + // When + CustomerResult foundResult = service.findById(existingId); + + // Then + assertThat(foundResult.id()).isEqualTo(existingId); + assertThat(foundResult) + .usingRecursiveComparison() + .ignoringFields("id") + .isEqualTo(createdResult); + } + + @Test + void findById_존재하지않는아이디인경우_예외발생() { + // Given + Long nonExistingId = 0L; + + // When & Then + assertThatThrownBy(() -> service.findById(nonExistingId)) + .isInstanceOf(CustomerNotFoundException.class); + } + + @Test + void findAll_저장된모든고객들반환() { + // Given + CustomerCreateData creatingData = new CustomerCreateData("FirstName", "LastName"); + CustomerResult createdResult = service.create(creatingData); + + // When + CustomerResults foundResults = service.findAll(); + + // Then + assertThat(foundResults.results()) + .usingRecursiveFieldByFieldElementComparator() + .contains(createdResult); + } + + @Test + void deleteById_존재하는아이디인경우_해당아이디고객삭제() { + // Given + CustomerCreateData creatingData = new CustomerCreateData("FirstName", "LastName"); + CustomerResult createdResult = service.create(creatingData); + + // When + Long deletingId = createdResult.id(); + service.deleteById(deletingId); + + // findByName 테스트해보기, exists + // Then + assertThatThrownBy(() -> service.findById(deletingId)) + .isInstanceOf(CustomerNotFoundException.class); + } +} diff --git a/jpashop/src/test/java/org/wonu606/jpashop/order/domain/OrderRepositoryTest.java b/jpashop/src/test/java/org/wonu606/jpashop/order/domain/OrderRepositoryTest.java new file mode 100644 index 000000000..4dfacfd7e --- /dev/null +++ b/jpashop/src/test/java/org/wonu606/jpashop/order/domain/OrderRepositoryTest.java @@ -0,0 +1,71 @@ +package org.wonu606.jpashop.order.domain; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.wonu606.jpashop.item.domain.Book; +import org.wonu606.jpashop.item.domain.ItemRepository; +import org.wonu606.jpashop.item.domain.PerformanceTicket; + +@DataJpaTest +class OrderRepositoryTest { + + private static final Logger log = LoggerFactory.getLogger(OrderRepositoryTest.class); + + @Autowired + private OrderRepository orderRepository; + + @Autowired + private ItemRepository itemRepository; + + private Order savedOrder; + + @BeforeEach + void setUp() { + // Given + Book book = new Book(19800, 90, "James", "978-0-7334-2609-4"); + Book savedBook = itemRepository.save(book); + + PerformanceTicket performanceTicket = new PerformanceTicket(89000, 432, "Opera House"); + PerformanceTicket savedTicket = itemRepository.save(performanceTicket); + + OrderLineItem orderLineItemForBook = + new OrderLineItem( + 19800, + 1, + savedBook); + + OrderLineItem orderLineItemForPerformanceTicket = + new OrderLineItem( + 898980, + 324, + savedTicket); + + Order order = new Order(LocalDateTime.now(), new ArrayList<>()); + order.addOrderLineItem(orderLineItemForBook); + order.addOrderLineItem(orderLineItemForPerformanceTicket); + + savedOrder = orderRepository.save(order); + } + + @Test + void findAll() { + List orderAllList = orderRepository.findAll(); + + log.info("orderAllList = {}", orderAllList); + } + + @Test + void findOne() { + Optional retrievedOrder = orderRepository.findByIdWithOrderLineItemsAndItems( + savedOrder.getId()); + log.info("{}", retrievedOrder.get()); + } +}