diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..649136dfb --- /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/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +*.yml diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..b4404448c --- /dev/null +++ b/build.gradle @@ -0,0 +1,37 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.2' + id 'io.spring.dependency-management' version '1.1.2' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + implementation 'org.springframework.boot:spring-boot-starter-validation' +} + +tasks.named('test') { + useJUnitPlatform() +} 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 100644 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/settings.gradle b/settings.gradle new file mode 100644 index 000000000..5cea63d0d --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'spring-jpa-mission' diff --git a/src/main/java/com/example/springjpamission/SpringJpaMissionApplication.java b/src/main/java/com/example/springjpamission/SpringJpaMissionApplication.java new file mode 100644 index 000000000..0f3403f32 --- /dev/null +++ b/src/main/java/com/example/springjpamission/SpringJpaMissionApplication.java @@ -0,0 +1,13 @@ +package com.example.springjpamission; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringJpaMissionApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringJpaMissionApplication.class, args); + } + +} diff --git a/src/main/java/com/example/springjpamission/config/DataSourceConfig.java b/src/main/java/com/example/springjpamission/config/DataSourceConfig.java new file mode 100644 index 000000000..99c103a8d --- /dev/null +++ b/src/main/java/com/example/springjpamission/config/DataSourceConfig.java @@ -0,0 +1,70 @@ +package com.example.springjpamission.config; + +import java.util.Properties; +import javax.sql.DataSource; +import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +public class DataSourceConfig { + + private static final String DRIVER = "org.h2.Driver"; + private static final String DB_URL = "jdbc:h2:tcp://localhost/~/test"; + private static final String USER = "sa"; + private static final String PASSWORD= ""; + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(DRIVER); + dataSource.setUrl(DB_URL); + dataSource.setUsername(USER); + dataSource.setPassword(PASSWORD); + + return dataSource; + } + + @Bean + public JpaVendorAdapter jpaVendorAdapter(JpaProperties jpaProperties) { + AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); + adapter.setShowSql(jpaProperties.isShowSql()); + adapter.setDatabasePlatform(jpaProperties.getDatabasePlatform()); + adapter.setGenerateDdl(jpaProperties.isGenerateDdl()); + return adapter; + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, + JpaVendorAdapter jpaVendorAdapter, + JpaProperties jpaProperties) { + LocalContainerEntityManagerFactoryBean em + = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource); + em.setPackagesToScan("com.example"); + em.setJpaVendorAdapter(jpaVendorAdapter); + + Properties properties = new Properties(); + properties.putAll(jpaProperties.getProperties()); + em.setJpaProperties(properties); + + return em; + } + + @Bean + public PlatformTransactionManager transactionManager( + LocalContainerEntityManagerFactoryBean entityManagerFactory) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory.getObject()); + + return transactionManager; + } + +} diff --git a/src/main/java/com/example/springjpamission/customer/domain/Customer.java b/src/main/java/com/example/springjpamission/customer/domain/Customer.java new file mode 100644 index 000000000..778e1a83b --- /dev/null +++ b/src/main/java/com/example/springjpamission/customer/domain/Customer.java @@ -0,0 +1,49 @@ +package com.example.springjpamission.customer.domain; + +import com.example.springjpamission.gobal.BaseEntity; +import com.example.springjpamission.order.domain.Order; +import jakarta.persistence.*; +import jakarta.validation.Valid; + +import java.util.ArrayList; +import java.util.List; + +@Table(name = "customers") +@Entity +public class Customer extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Valid + @Embedded + @Column(nullable = false) + private Name name; + + @OneToMany(mappedBy = "customer") + private List orders = new ArrayList<>(); + + protected Customer() { } + + public Customer(Name name) { + this.name = name; + } + + public void changeName(Name name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public Name getName() { + return name; + } + + public List getOrders() { + return orders; + } + +} diff --git a/src/main/java/com/example/springjpamission/customer/domain/CustomerRepository.java b/src/main/java/com/example/springjpamission/customer/domain/CustomerRepository.java new file mode 100644 index 000000000..238b5e1ae --- /dev/null +++ b/src/main/java/com/example/springjpamission/customer/domain/CustomerRepository.java @@ -0,0 +1,7 @@ +package com.example.springjpamission.customer.domain; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CustomerRepository extends JpaRepository { + +} diff --git a/src/main/java/com/example/springjpamission/customer/domain/Name.java b/src/main/java/com/example/springjpamission/customer/domain/Name.java new file mode 100644 index 000000000..789dab6cc --- /dev/null +++ b/src/main/java/com/example/springjpamission/customer/domain/Name.java @@ -0,0 +1,55 @@ +package com.example.springjpamission.customer.domain; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +import java.util.Objects; + +@Embeddable +public class Name { + + private String firstName; + + private String lastName; + + protected Name() { } + + public Name(String firstName, String lastName) { + validateName(firstName,lastName ); + this.firstName = firstName; + this.lastName = lastName; + } + + private void validateName(String firstName, String lastName) { + if (firstName == null || firstName.isBlank()) { + throw new IllegalArgumentException(); + } + if (lastName == null || lastName.isBlank()) { + throw new IllegalArgumentException(); + } + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Name name = (Name) o; + return Objects.equals(firstName, name.firstName) && Objects.equals(lastName, name.lastName); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } + +} diff --git a/src/main/java/com/example/springjpamission/customer/service/CustomerService.java b/src/main/java/com/example/springjpamission/customer/service/CustomerService.java new file mode 100644 index 000000000..8c034639c --- /dev/null +++ b/src/main/java/com/example/springjpamission/customer/service/CustomerService.java @@ -0,0 +1,52 @@ +package com.example.springjpamission.customer.service; + +import com.example.springjpamission.customer.domain.Customer; +import com.example.springjpamission.customer.domain.CustomerRepository; +import com.example.springjpamission.customer.domain.Name; +import com.example.springjpamission.customer.service.dto.CustomerResponses; +import com.example.springjpamission.customer.service.dto.SaveCustomerRequest; +import com.example.springjpamission.customer.service.dto.CustomerResponse; +import com.example.springjpamission.customer.service.dto.UpdateCustomerRequest; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +@Service +public class CustomerService { + + private final CustomerRepository customerRepository; + + public CustomerService(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + public CustomerResponse saveCustomer(SaveCustomerRequest saveCustomerRequest) { + Customer customer = new Customer( + new Name(saveCustomerRequest.firstName(), saveCustomerRequest.lastName())); + return CustomerResponse.of(customerRepository.save(customer)); + } + + public CustomerResponse updateCustomer(UpdateCustomerRequest updateCustomerRequest) { + Customer findCustomer = customerRepository.findById(updateCustomerRequest.id()) + .orElseThrow(() -> new EntityNotFoundException("해당 customer는 존재하지 않습니다.")); + + findCustomer.changeName( + new Name(updateCustomerRequest.firstName(), updateCustomerRequest.lastName())); + return CustomerResponse.of(findCustomer); + } + + @Transactional(readOnly = true) + public CustomerResponses findAll(Pageable pageable) { + return CustomerResponses.of(customerRepository.findAll(pageable)); + } + + public void deleteById(Long id) { + customerRepository.findById(id) + .orElseThrow(()->new EntityNotFoundException("해당 customer는 존재하지 않습니다.")); + + customerRepository.deleteById(id); + } + +} diff --git a/src/main/java/com/example/springjpamission/customer/service/dto/CustomerResponse.java b/src/main/java/com/example/springjpamission/customer/service/dto/CustomerResponse.java new file mode 100644 index 000000000..830b3c7ea --- /dev/null +++ b/src/main/java/com/example/springjpamission/customer/service/dto/CustomerResponse.java @@ -0,0 +1,13 @@ +package com.example.springjpamission.customer.service.dto; + +import com.example.springjpamission.customer.domain.Customer; + +public record CustomerResponse(Long id, String firstName, String lastName) { + + public static CustomerResponse of(Customer customer) { + return new CustomerResponse(customer.getId(), + customer.getName().getFirstName(), + customer.getName().getLastName()); + } + +} diff --git a/src/main/java/com/example/springjpamission/customer/service/dto/CustomerResponses.java b/src/main/java/com/example/springjpamission/customer/service/dto/CustomerResponses.java new file mode 100644 index 000000000..a4dbd05eb --- /dev/null +++ b/src/main/java/com/example/springjpamission/customer/service/dto/CustomerResponses.java @@ -0,0 +1,18 @@ +package com.example.springjpamission.customer.service.dto; + +import com.example.springjpamission.customer.domain.Customer; +import org.springframework.data.domain.Slice; + +import java.util.List; +import java.util.stream.Collectors; + +public record CustomerResponses(List customerResponses) { + + public static CustomerResponses of(Slice customers) { + List responses = customers.stream() + .map(CustomerResponse::of) + .collect(Collectors.toList()); + return new CustomerResponses(responses); + } + +} diff --git a/src/main/java/com/example/springjpamission/customer/service/dto/SaveCustomerRequest.java b/src/main/java/com/example/springjpamission/customer/service/dto/SaveCustomerRequest.java new file mode 100644 index 000000000..42b5f0ba1 --- /dev/null +++ b/src/main/java/com/example/springjpamission/customer/service/dto/SaveCustomerRequest.java @@ -0,0 +1,4 @@ +package com.example.springjpamission.customer.service.dto; + +public record SaveCustomerRequest(String firstName, + String lastName) { } diff --git a/src/main/java/com/example/springjpamission/customer/service/dto/UpdateCustomerRequest.java b/src/main/java/com/example/springjpamission/customer/service/dto/UpdateCustomerRequest.java new file mode 100644 index 000000000..19a4414b3 --- /dev/null +++ b/src/main/java/com/example/springjpamission/customer/service/dto/UpdateCustomerRequest.java @@ -0,0 +1,5 @@ +package com.example.springjpamission.customer.service.dto; + +public record UpdateCustomerRequest(Long id, + String firstName, + String lastName) { } diff --git a/src/main/java/com/example/springjpamission/gobal/BaseEntity.java b/src/main/java/com/example/springjpamission/gobal/BaseEntity.java new file mode 100644 index 000000000..451963665 --- /dev/null +++ b/src/main/java/com/example/springjpamission/gobal/BaseEntity.java @@ -0,0 +1,36 @@ +package com.example.springjpamission.gobal; + +import jakarta.persistence.Column; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.PrePersist; +import jakarta.persistence.PreUpdate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +@MappedSuperclass +public abstract class BaseEntity { + + private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + @Column(updatable = false, nullable = false) + private String createAt; + + @Column(nullable = false) + private String lastUpdatedAt; + + protected BaseEntity() { } + + @PrePersist + public void prePersist() { + LocalDateTime now = LocalDateTime.now(); + createAt = now.format(DateTimeFormatter.ofPattern(DATE_FORMAT)); + lastUpdatedAt = now.format(DateTimeFormatter.ofPattern(DATE_FORMAT)); + } + + @PreUpdate + public void preUpdate() { + lastUpdatedAt = LocalDateTime.now() + .format(DateTimeFormatter.ofPattern(DATE_FORMAT)); + } + +} diff --git a/src/main/java/com/example/springjpamission/order/domain/Car.java b/src/main/java/com/example/springjpamission/order/domain/Car.java new file mode 100644 index 000000000..3aaec5950 --- /dev/null +++ b/src/main/java/com/example/springjpamission/order/domain/Car.java @@ -0,0 +1,34 @@ +package com.example.springjpamission.order.domain; + +import jakarta.persistence.Column; +import jakarta.persistence.DiscriminatorValue; +import jakarta.persistence.Entity; + +@DiscriminatorValue("CAR") +@Entity +public class Car extends Item { + + private static final int ZERO = 0; + + @Column + private int power; + + protected Car() { } + + public Car(Price price, int stockQuantity, int power) { + super(price, stockQuantity); + validatePower(power); + this.power = power; + } + + private void validatePower(int power) { + if(power < ZERO) { + throw new IllegalArgumentException(); + } + } + + public int getPower() { + return power; + } + +} diff --git a/src/main/java/com/example/springjpamission/order/domain/Food.java b/src/main/java/com/example/springjpamission/order/domain/Food.java new file mode 100644 index 000000000..a1ee9dc80 --- /dev/null +++ b/src/main/java/com/example/springjpamission/order/domain/Food.java @@ -0,0 +1,28 @@ +package com.example.springjpamission.order.domain; + +import jakarta.persistence.Column; +import jakarta.persistence.DiscriminatorValue; +import jakarta.persistence.Entity; + +@DiscriminatorValue("FOOD") +@Entity +public class Food extends Item { + + @Column + private String chef; + + protected Food() { } + + public Food(Price price, int stockQuantity, String chef) { + super(price, stockQuantity); + validateChef(chef); + this.chef = chef; + } + + private void validateChef(String chef) { + if (chef == null || chef.isBlank()) { + throw new IllegalArgumentException(); + } + } + +} diff --git a/src/main/java/com/example/springjpamission/order/domain/Item.java b/src/main/java/com/example/springjpamission/order/domain/Item.java new file mode 100644 index 000000000..8dc15b35b --- /dev/null +++ b/src/main/java/com/example/springjpamission/order/domain/Item.java @@ -0,0 +1,31 @@ +package com.example.springjpamission.order.domain; + +import com.example.springjpamission.gobal.BaseEntity; +import jakarta.persistence.*; + + +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "DTYPE") +@Table(name = "items") +@Entity +public abstract class Item extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Embedded + @Column(nullable = false) + private Price price; + + @Column(nullable = false) + private int stockQuantity; + + protected Item() {} + + public Item(Price price, int stockQuantity) { + this.price = price; + this.stockQuantity = stockQuantity; + } + +} diff --git a/src/main/java/com/example/springjpamission/order/domain/Order.java b/src/main/java/com/example/springjpamission/order/domain/Order.java new file mode 100644 index 000000000..19d526434 --- /dev/null +++ b/src/main/java/com/example/springjpamission/order/domain/Order.java @@ -0,0 +1,57 @@ +package com.example.springjpamission.order.domain; + +import com.example.springjpamission.customer.domain.Customer; +import com.example.springjpamission.gobal.BaseEntity; +import jakarta.persistence.*; + +import java.util.ArrayList; +import java.util.List; + +@Table(name = "orders") +@Entity +public class Order extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String memo; + + @Embedded + @Column(nullable = false) + private Price price; + + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "customer_id", referencedColumnName = "id") + private Customer customer; + + @OneToMany(mappedBy = "order", orphanRemoval = true) + private List orderItems = new ArrayList<>(); + + protected Order() { } + + public Order(String memo) { + this.memo = memo; + } + + public Order(String memo, Price price, Customer customer) { + this.memo = memo; + this.price = price; + this.customer = customer; + } + + public void changeCustomer(Customer customer) { + this.customer = customer; + customer.getOrders().add(this); + } + + public Customer getCustomer() { + return customer; + } + + public List getOrderItems() { + return orderItems; + } +} diff --git a/src/main/java/com/example/springjpamission/order/domain/OrderItem.java b/src/main/java/com/example/springjpamission/order/domain/OrderItem.java new file mode 100644 index 000000000..ed14824ef --- /dev/null +++ b/src/main/java/com/example/springjpamission/order/domain/OrderItem.java @@ -0,0 +1,65 @@ +package com.example.springjpamission.order.domain; + +import com.example.springjpamission.gobal.BaseEntity; +import jakarta.persistence.*; + +import java.util.Objects; + +@Table(name = "order_items") +@Entity +public class OrderItem extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Embedded + @Column(nullable = false) + private Price price; + + @ManyToOne(cascade = CascadeType.PERSIST) + @JoinColumn(name = "order_id", referencedColumnName = "id") + private Order order; + + @ManyToOne + @JoinColumn(name = "item_id", referencedColumnName = "id") + private Item item; + + protected OrderItem() {} + + public OrderItem(Price price, Order order, Item items) { + this.price = price; + this.order = order; + this.item = items; + } + + public Long getId() { + return id; + } + + public Price getPrice() { + return price; + } + + public Order getOrder() { + return order; + } + + public Item getItem() { + return item; + } + + public void changeOrder(Order order) { + if (Objects.nonNull(this.order)) { + this.order.getOrderItems().remove(this); + } + + this.order = order; + order.getOrderItems().add(this); + } + + public void changeItem(Item item) { // 방금 아까 봤던 오더 + this.item = item; + } + +} diff --git a/src/main/java/com/example/springjpamission/order/domain/OrderRepository.java b/src/main/java/com/example/springjpamission/order/domain/OrderRepository.java new file mode 100644 index 000000000..b0ec5e493 --- /dev/null +++ b/src/main/java/com/example/springjpamission/order/domain/OrderRepository.java @@ -0,0 +1,7 @@ +package com.example.springjpamission.order.domain; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface OrderRepository extends JpaRepository { + +} diff --git a/src/main/java/com/example/springjpamission/order/domain/Price.java b/src/main/java/com/example/springjpamission/order/domain/Price.java new file mode 100644 index 000000000..bea2b57eb --- /dev/null +++ b/src/main/java/com/example/springjpamission/order/domain/Price.java @@ -0,0 +1,23 @@ +package com.example.springjpamission.order.domain; + +import jakarta.persistence.Embeddable; + +@Embeddable +public class Price{ + + private int cost; + + protected Price() { } + + public Price(int cost) { + if (cost < 0) { + throw new IllegalArgumentException("가격 : " + cost); + } + this.cost = cost; + } + + public int getCost(){ + return cost; + } + +} diff --git a/src/test/java/com/example/springjpamission/PersistenceContextTest.java b/src/test/java/com/example/springjpamission/PersistenceContextTest.java new file mode 100644 index 000000000..365998c9c --- /dev/null +++ b/src/test/java/com/example/springjpamission/PersistenceContextTest.java @@ -0,0 +1,77 @@ +package com.example.springjpamission; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import com.example.springjpamission.customer.domain.Customer; +import com.example.springjpamission.customer.domain.Name; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ActiveProfiles; + +@ActiveProfiles("test") +@DataJpaTest +class PersistenceContextTest { + + @Autowired + EntityManagerFactory entityManagerFactory; + + @Test + @DisplayName("고객의 정보를 저장한 후 영속성 컨텍스트를 초기화한 후 저장소에서 정보를 가져왔을 때 같은 primary key로 저장되었는지 확인한다.") + void save() { + //given + EntityManager em = entityManagerFactory.createEntityManager(); + EntityTransaction transaction = em.getTransaction(); + + //when + transaction.begin(); + Name name = new Name("영운", "윤"); + Customer customer = new Customer(name); + + em.persist(customer); + + transaction.commit(); + em.clear(); + + //then + Customer findCustomer = em.find(Customer.class, customer.getId()); + assertThat(findCustomer.getId()).isEqualTo(customer.getId()); + assertThat(findCustomer.getName().getFirstName()).isEqualTo("영운"); + assertThat(findCustomer.getName().getLastName()).isEqualTo("윤"); + } + + @Test + @DisplayName("고객의 정보를 저장소에 저장한 후 이를 수정할 때 의도한 이름으로 수정되었는지 확인한다.") + void update() { + //given + EntityManager em = entityManagerFactory.createEntityManager(); + EntityTransaction transaction = em.getTransaction(); + + transaction.begin(); + Name name = new Name("영운", "윤"); + Customer customer = new Customer(name); + em.persist(customer); + + transaction.commit(); + + //when + transaction.begin(); + Customer findCustomer = em.find(Customer.class, customer.getId()); + Name newName = new Name("별", "김"); + findCustomer.changeName(newName); + em.persist(findCustomer); + + transaction.commit(); + + //then + em.clear(); + Customer updatedCustomer = em.find(Customer.class, findCustomer.getId()); + + assertThat(updatedCustomer.getName()).isEqualTo(newName); + } + +} diff --git a/src/test/java/com/example/springjpamission/customer/domain/CustomerServiceTest.java b/src/test/java/com/example/springjpamission/customer/domain/CustomerServiceTest.java new file mode 100644 index 000000000..05f85853a --- /dev/null +++ b/src/test/java/com/example/springjpamission/customer/domain/CustomerServiceTest.java @@ -0,0 +1,108 @@ +package com.example.springjpamission.customer.domain; + +import com.example.springjpamission.customer.service.CustomerService; +import com.example.springjpamission.customer.service.dto.CustomerResponse; +import com.example.springjpamission.customer.service.dto.CustomerResponses; +import com.example.springjpamission.customer.service.dto.SaveCustomerRequest; +import com.example.springjpamission.customer.service.dto.UpdateCustomerRequest; +import jakarta.persistence.EntityNotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.PageRequest; +import org.springframework.test.context.ActiveProfiles; + +import java.util.List; +import java.util.Random; + +import org.springframework.transaction.annotation.Transactional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchException; + +@ActiveProfiles("test") +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) +@Transactional +class CustomerServiceTest { + + @Autowired + CustomerService customerService; + + @Autowired + CustomerRepository customerRepository; + + Long setUpCustomerId; + + @BeforeEach + void setUp() { + Customer customer = new Customer(new Name("영운", "윤")); + customerRepository.save(customer); + setUpCustomerId = customer.getId(); + } + + @Test + @DisplayName("customer를 저장 후 조회하여 이름을 확인한다.") + void saveCustomer() { + //given + SaveCustomerRequest saveCustomerRequest = new SaveCustomerRequest("별", "김"); + + //when + CustomerResponse customerResponse = customerService.saveCustomer(saveCustomerRequest); + + //then + Customer findCustomer = customerRepository.findById(customerResponse.id()).get(); + assertThat(findCustomer.getName().getFirstName()).isEqualTo("별"); + assertThat(findCustomer.getName().getLastName()).isEqualTo("김"); + } + + @Test + @DisplayName("setUp()에서 넣은 데이터를 업데이트 했을 때 올바른 이름으로 업데이트 되었는지 확인한다.") + void updateCustomer() { + //given + UpdateCustomerRequest updateCustomerRequest = new UpdateCustomerRequest(setUpCustomerId, + "별", "김"); + + //when + customerService.updateCustomer(updateCustomerRequest); + + //then + Customer findCustomer = customerRepository.findById(setUpCustomerId).get(); + assertThat(findCustomer.getName().getFirstName()).isEqualTo("별"); + assertThat(findCustomer.getName().getLastName()).isEqualTo("김"); + } + + @Test + @DisplayName("전체 데이터 조회시 setUp()에 넣은 데이터를 조회하여 사이즈가 1이 된다.") + void findAll() { + //when + PageRequest pageSize = PageRequest.of(0, 10); + CustomerResponses findCustomers = customerService.findAll(pageSize); + + //then + assertThat(findCustomers.customerResponses().size()).isEqualTo(1); + } + + @Test + @DisplayName("고객 아이디로 삭제되어 저장소 사이즈가 0이 된다.") + void deleteById() { + //when + customerService.deleteById(setUpCustomerId); + + //then + List findCustomers = customerRepository.findAll(); + assertThat(findCustomers.size()).isEqualTo(0); + } + + @Test + @DisplayName("존재하지 않는 고객 아이디로 삭제 요청시 EntityNotFoundException가 발생한다.") + void deleteByNotExistId() { + //when + Exception exception = catchException(() -> customerService.deleteById(new Random().nextLong())); + + //then + assertThat(exception).isInstanceOf(EntityNotFoundException.class); + } + +} diff --git a/src/test/java/com/example/springjpamission/customer/domain/RelationMappingTest.java b/src/test/java/com/example/springjpamission/customer/domain/RelationMappingTest.java new file mode 100644 index 000000000..7aa911dc7 --- /dev/null +++ b/src/test/java/com/example/springjpamission/customer/domain/RelationMappingTest.java @@ -0,0 +1,57 @@ +package com.example.springjpamission.customer.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.example.springjpamission.order.domain.Car; +import com.example.springjpamission.order.domain.Order; +import com.example.springjpamission.order.domain.OrderItem; +import com.example.springjpamission.order.domain.Price; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ActiveProfiles; + +@ActiveProfiles("test") +@DataJpaTest +class RelationMappingTest { + + @Autowired + EntityManagerFactory entityManagerFactory; + + @Test + @DisplayName("order, order_item, item간 매핑이 잘 되어있는지 확인한다.") + void order_orderItem_item_mappingTest() { + //given + EntityManager em = entityManagerFactory.createEntityManager(); + EntityTransaction transaction = em.getTransaction(); + Customer customer = new Customer(new Name("별", "김")); + + Order order = new Order("test memo", new Price(1000), customer); + Car car = new Car(new Price(1000), 1, 500); + OrderItem orderItem = new OrderItem(new Price(1000), order, car); + + //when + transaction.begin(); + + em.persist(customer); + em.persist(car); + em.persist(orderItem); + + transaction.commit(); + em.clear(); + + //then + Order updatedOrder = em.find(Order.class, orderItem.getId()); + OrderItem updatedOrderItem = em.find(OrderItem.class, orderItem.getId()); + Car item = (Car) updatedOrderItem.getItem(); + + assertThat(updatedOrder.getOrderItems().get(0).getPrice().getCost()).isEqualTo(1000); + assertThat(item.getPower()).isEqualTo(500); + } + +}