diff --git a/sanho/jpa-ex/.gitattributes b/sanho/jpa-ex/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/sanho/jpa-ex/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/sanho/jpa-ex/.gitignore b/sanho/jpa-ex/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/sanho/jpa-ex/.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/sanho/jpa-ex/build.gradle b/sanho/jpa-ex/build.gradle new file mode 100644 index 0000000..85c2a8b --- /dev/null +++ b/sanho/jpa-ex/build.gradle @@ -0,0 +1,40 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.5' + id 'io.spring.dependency-management' version '1.1.6' +} + +group = 'umc' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +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' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/sanho/jpa-ex/gradle/wrapper/gradle-wrapper.jar b/sanho/jpa-ex/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/sanho/jpa-ex/gradle/wrapper/gradle-wrapper.jar differ diff --git a/sanho/jpa-ex/gradle/wrapper/gradle-wrapper.properties b/sanho/jpa-ex/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df97d72 --- /dev/null +++ b/sanho/jpa-ex/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/sanho/jpa-ex/gradlew b/sanho/jpa-ex/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/sanho/jpa-ex/gradlew @@ -0,0 +1,252 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/sanho/jpa-ex/gradlew.bat b/sanho/jpa-ex/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/sanho/jpa-ex/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +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/sanho/jpa-ex/settings.gradle b/sanho/jpa-ex/settings.gradle new file mode 100644 index 0000000..de60b54 --- /dev/null +++ b/sanho/jpa-ex/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'jpa-ex' diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/JpaExApplication.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/JpaExApplication.java new file mode 100644 index 0000000..cb1bc39 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/JpaExApplication.java @@ -0,0 +1,15 @@ +package umc.jpa_ex; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +@EnableJpaAuditing +public class JpaExApplication { + + public static void main(String[] args) { + SpringApplication.run(JpaExApplication.class, args); + } + +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/FoodCategory.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/FoodCategory.java new file mode 100644 index 0000000..ee6b30c --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/FoodCategory.java @@ -0,0 +1,27 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; +import umc.jpa_ex.domain.mapping.SelectCategory; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class FoodCategory extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 20) + private String name; + + @OneToMany(mappedBy = "foodCategory", cascade = CascadeType.ALL) + private List selectCategoryList = new ArrayList<>(); +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/MarketingAlarm.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/MarketingAlarm.java new file mode 100644 index 0000000..6cfef28 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/MarketingAlarm.java @@ -0,0 +1,29 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class MarketingAlarm extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Boolean isConfirmed; // 미션 확인 여부 + + @Column(nullable = false, length = 30) + private String title; + + @Column(columnDefinition = "TEXT") + private String body; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Member.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Member.java new file mode 100644 index 0000000..07f9e0e --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Member.java @@ -0,0 +1,69 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; +import umc.jpa_ex.domain.embedded.Address; +import umc.jpa_ex.domain.enums.Gender; +import umc.jpa_ex.domain.enums.MemberStatus; +import umc.jpa_ex.domain.mapping.MemberAgree; +import umc.jpa_ex.domain.mapping.MemberMission; +import umc.jpa_ex.domain.mapping.SelectCategory; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Member extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 10) + private String name; + + @Column(nullable = false, length = 10) + private String nickname; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 10) + private Gender gender; + + private LocalDate birthdate; // date 타입이라 LocalDate + + @Embedded + private Address address; // 내장 타입 + + private int point; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 15) + private MemberStatus status; + + private LocalDateTime inactiveDate; // datetime 타입이므로 LocalDateTime + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) // CascadeType.ALL로 인해 persist(member) 하면 같이 persist 됨. + private List memberAgreeList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + private List selectCategoryList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + private List reviewList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + private List memberMissionList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + private List reviewAlarmList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + private List marketingAlarmList = new ArrayList<>(); +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Mission.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Mission.java new file mode 100644 index 0000000..f1fa46d --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Mission.java @@ -0,0 +1,40 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; +import umc.jpa_ex.domain.mapping.MemberMission; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Mission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) // 데이터 삽입하면 자동 id를 넣어줌. 1,2,3,4,5에서 1 삭제 되어도 2,3,4,5 그대로 남아있음 + private Long id; + + private int reward; + + @Column(nullable = false, length = 30) + private String title; + + @Column(columnDefinition = "TEXT") + private String body; + + private LocalDateTime deadline; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + @OneToMany(mappedBy = "mission", cascade = CascadeType.ALL) + private List memberMissionList = new ArrayList<>(); +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Region.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Region.java new file mode 100644 index 0000000..7f62f2f --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Region.java @@ -0,0 +1,26 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Region extends BaseEntity{ + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 20) + private String name; + + @OneToMany(mappedBy = "region", cascade = CascadeType.ALL) + private List storeList = new ArrayList<>(); +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Review.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Review.java new file mode 100644 index 0000000..b2eff46 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Review.java @@ -0,0 +1,35 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Review extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Double rating; // 리뷰 별점 + + private String content; // 리뷰 내용, String은 기본이 varchar(255) + + @Column(columnDefinition = "TEXT") + private String reviewPictureUrl; // 리뷰 사진 URL + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + +} + + diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/ReviewAlarm.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/ReviewAlarm.java new file mode 100644 index 0000000..f743b92 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/ReviewAlarm.java @@ -0,0 +1,29 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class ReviewAlarm extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Boolean isConfirmed; // 미션 확인 여부 + + @Column(nullable = false, length = 30) + private String title; + + @Column(columnDefinition = "TEXT") + private String body; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Store.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Store.java new file mode 100644 index 0000000..167ade2 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Store.java @@ -0,0 +1,64 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; +import umc.jpa_ex.domain.embedded.Address; +import umc.jpa_ex.domain.enums.StoreStatus; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Store extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 10) + private String name; + + @Column(nullable = false, length = 20) + private String information; // 가게 정보 + + @Column(columnDefinition = "TEXT") + private String storePictureUrl; // 가게 사진 URL + + @Embedded + private Address address; + + @Column(nullable = false, length = 20) + private String foodCategory; // 가게 음식 카테고리 + + @Column(nullable = false, length = 20) + private String phoneNumber; + + private String description; // 가게 소개글 + + private Double rating; // 가게 별점 + + private int reviewCount; // 가게 리뷰 개수 + + private String operationHour; // 가게 운영 시간 + + private String closeDay; // 가게 휴무일 + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 15) + private StoreStatus status; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "region_id") + private Region region; + + @OneToMany(mappedBy = "store", cascade = CascadeType.ALL) + private List reviewList = new ArrayList<>(); + + @OneToMany(mappedBy = "store", cascade = CascadeType.ALL) + private List missionList = new ArrayList<>(); +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Terms.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Terms.java new file mode 100644 index 0000000..9e4715c --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/Terms.java @@ -0,0 +1,32 @@ +package umc.jpa_ex.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.common.BaseEntity; +import umc.jpa_ex.domain.mapping.MemberAgree; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Terms extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 20) + private String title; + + @Column(columnDefinition = "TEXT") + private String body; + + private Boolean optional; + + @OneToMany(mappedBy = "terms", cascade = CascadeType.ALL) + private List memberAgreeList = new ArrayList<>(); +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/common/BaseEntity.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/common/BaseEntity.java new file mode 100644 index 0000000..1eca2bc --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/common/BaseEntity.java @@ -0,0 +1,25 @@ +package umc.jpa_ex.domain.common; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@Getter +public abstract class BaseEntity { + + @CreatedDate + @Column(columnDefinition = "DATETIME(6)") + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(columnDefinition = "DATETIME(6)") + private LocalDateTime updatedAt; +} \ No newline at end of file diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/embedded/Address.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/embedded/Address.java new file mode 100644 index 0000000..40368c6 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/embedded/Address.java @@ -0,0 +1,22 @@ +package umc.jpa_ex.domain.embedded; + +import jakarta.persistence.Embeddable; +import lombok.Getter; + +@Embeddable // 어딘가 내장이 될 수 있다. +@Getter +public class Address { + + private String city; + private String street; + private String zipcode; + + protected Address() { + } + + public Address(String city, String street, String zipcode) { + this.city = city; + this.street = street; + this.zipcode = zipcode; + } +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/Gender.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/Gender.java new file mode 100644 index 0000000..dc474a1 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/Gender.java @@ -0,0 +1,5 @@ +package umc.jpa_ex.domain.enums; + +public enum Gender { + MALE, FEMALE; +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/MemberStatus.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/MemberStatus.java new file mode 100644 index 0000000..b91ec72 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/MemberStatus.java @@ -0,0 +1,5 @@ +package umc.jpa_ex.domain.enums; + +public enum MemberStatus { + ACTIVE, INACTIVE; +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/MissionStatus.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/MissionStatus.java new file mode 100644 index 0000000..5a13b74 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/MissionStatus.java @@ -0,0 +1,5 @@ +package umc.jpa_ex.domain.enums; + +public enum MissionStatus { + CHALLENGING, COMPLETE; +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/StoreStatus.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/StoreStatus.java new file mode 100644 index 0000000..9e5d41b --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/enums/StoreStatus.java @@ -0,0 +1,5 @@ +package umc.jpa_ex.domain.enums; + +public enum StoreStatus { + OPEN, CLOSE; +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/MemberAgree.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/MemberAgree.java new file mode 100644 index 0000000..585c03e --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/MemberAgree.java @@ -0,0 +1,27 @@ +package umc.jpa_ex.domain.mapping; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.Member; +import umc.jpa_ex.domain.Terms; +import umc.jpa_ex.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class MemberAgree extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "terms_id") + private Terms terms; +} \ No newline at end of file diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/MemberMission.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/MemberMission.java new file mode 100644 index 0000000..bcc68ca --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/MemberMission.java @@ -0,0 +1,32 @@ +package umc.jpa_ex.domain.mapping; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.Member; +import umc.jpa_ex.domain.Mission; +import umc.jpa_ex.domain.common.BaseEntity; +import umc.jpa_ex.domain.enums.MissionStatus; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class MemberMission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 20) + private MissionStatus status; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "mission_id") + private Mission mission; +} diff --git a/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/SelectCategory.java b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/SelectCategory.java new file mode 100644 index 0000000..88dc788 --- /dev/null +++ b/sanho/jpa-ex/src/main/java/umc/jpa_ex/domain/mapping/SelectCategory.java @@ -0,0 +1,27 @@ +package umc.jpa_ex.domain.mapping; + +import jakarta.persistence.*; +import lombok.*; +import umc.jpa_ex.domain.FoodCategory; +import umc.jpa_ex.domain.Member; +import umc.jpa_ex.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class SelectCategory extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "food_category_id") + private FoodCategory foodCategory; +} diff --git a/sanho/jpa-ex/src/main/resources/application.yml b/sanho/jpa-ex/src/main/resources/application.yml new file mode 100644 index 0000000..99b2bcd --- /dev/null +++ b/sanho/jpa-ex/src/main/resources/application.yml @@ -0,0 +1,20 @@ +# local DB ?? +spring: + datasource: + url: jdbc:mysql://localhost:3306/jpa_ex + username: root + password: ssh159357! + driver-class-name: com.mysql.cj.jdbc.Driver + sql: + init: + mode: never + jpa: + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL8Dialect + show_sql: true + format_sql: true + use_sql_comments: true + hbm2ddl: + auto: create # ???? create, ???? update. (create? ?? ??? ?? ????? ?? ??? ?) + default_batch_fetch_size: 1000 \ No newline at end of file diff --git a/sanho/jpa-ex/src/test/java/umc/jpa_ex/JpaExApplicationTests.java b/sanho/jpa-ex/src/test/java/umc/jpa_ex/JpaExApplicationTests.java new file mode 100644 index 0000000..dcbd4fc --- /dev/null +++ b/sanho/jpa-ex/src/test/java/umc/jpa_ex/JpaExApplicationTests.java @@ -0,0 +1,13 @@ +package umc.jpa_ex; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class JpaExApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/sanho/spring/.gitignore b/sanho/spring/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/sanho/spring/.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/sanho/spring/build.gradle b/sanho/spring/build.gradle new file mode 100644 index 0000000..72d02b0 --- /dev/null +++ b/sanho/spring/build.gradle @@ -0,0 +1,82 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.4' + id 'io.spring.dependency-management' version '1.1.6' +// id "com.ewerk.gradle.plugins.querydsl" version "1.0.10" // dependencies에 넣으면 안 써도 됨 +} + +group = 'umc' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' // swagger + + // queryDSL + implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta' + annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jakarta" + annotationProcessor "jakarta.annotation:jakarta.annotation-api" + annotationProcessor "jakarta.persistence:jakarta.persistence-api" + + //test 롬복 사용 + testCompileOnly 'org.projectlombok:lombok' + testAnnotationProcessor 'org.projectlombok:lombok' + + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + +// implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.9.0' +} + +tasks.named('test') { + useJUnitPlatform() +} + +// Querydsl 설정부 +// Clean 태스크 설정 +clean { + delete file('src/main/generated') +} + +//sourceSets { +// main { +// java { +// srcDirs = ['src/main/java', 'src/main/resources'] +// } +// } +//} + +//def generated = 'src/main/generated' +// +//querydsl { +// jpa = true +// querydslSourcesDir = generated +//} +//sourceSets { +// main.java.srcDir generated +//} +// +//compileQuerydsl{ +// options.annotationProcessorPath = configurations.querydsl // configurations.annotationProcessor +//} diff --git a/sanho/spring/gradle/wrapper/gradle-wrapper.jar b/sanho/spring/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e69de29 diff --git a/sanho/spring/gradle/wrapper/gradle-wrapper.properties b/sanho/spring/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a80b22c --- /dev/null +++ b/sanho/spring/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/sanho/spring/gradlew b/sanho/spring/gradlew new file mode 100644 index 0000000..fcb6fca --- /dev/null +++ b/sanho/spring/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/sanho/spring/gradlew.bat b/sanho/spring/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/sanho/spring/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/sanho/spring/settings.gradle b/sanho/spring/settings.gradle new file mode 100644 index 0000000..ebf1ef8 --- /dev/null +++ b/sanho/spring/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'spring' diff --git a/sanho/spring/src/main/java/umc/spring/Application.java b/sanho/spring/src/main/java/umc/spring/Application.java new file mode 100644 index 0000000..05e37ce --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/Application.java @@ -0,0 +1,37 @@ +package umc.spring; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import umc.spring.service.store.StoreQueryService; + +@SpringBootApplication +@EnableJpaAuditing +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public CommandLineRunner run(ApplicationContext context) { + return args -> { + StoreQueryService storeService = context.getBean(StoreQueryService.class); + + // 파라미터 값 설정 + String name = "요아정"; + Float score = 4.0f; + + // 쿼리 메서드 호출 및 쿼리 문자열과 파라미터 출력 + System.out.println("Executing findStoresByNameAndScore with parameters:"); + System.out.println("Name: " + name); + System.out.println("Score: " + score); + + storeService.findStoresByNameAndScore(name, score) + .forEach(System.out::println); + }; + } +} diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/ApiResponse.java b/sanho/spring/src/main/java/umc/spring/apipayload/ApiResponse.java new file mode 100644 index 0000000..3f48546 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/ApiResponse.java @@ -0,0 +1,41 @@ +package umc.spring.apipayload; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import umc.spring.apipayload.code.BaseCode; +import umc.spring.apipayload.code.status.SuccessStatus; + +@Getter +@AllArgsConstructor +@JsonPropertyOrder({"isSuccess", "code", "message", "result"}) // 필드 순서 명시적 지정 +public class ApiResponse { // "일관된" 에러 메시지 응답 Dto + + @JsonProperty("isSuccess") // 필드 이름 지정, 여기 같은 경우는 이미 isSuccess라 굳이 안 적어도 되긴 함. + private final Boolean isSuccess; + private final String code; + private final String message; + @JsonInclude(JsonInclude.Include.NON_NULL) // Null은 포함하지 않음 + private T result; // 제네릭 + + + // 성공한 경우 응답 생성 + public static ApiResponse onSuccess(T result){ // 제네릭 메서드, result가 어디서 오는지 잘 확인. + return new ApiResponse<>(true, SuccessStatus._OK.getCode() , SuccessStatus._OK.getMessage(), result); + } + + // 기존의 onSuccess 메서드보다 좀 더 유연하게 특정 상태 코드나 메시지를 커스터마이징해서 사용할 수 있다. + + public static ApiResponse of(BaseCode code, T result){ // HttpStatus까지, code는 인터페이스로 SuccessStatus가 이를 구현함 + return new ApiResponse<>(true, code.getReasonHttpStatus().getCode() , code.getReasonHttpStatus().getMessage(), result); + } + + + // 실패한 경우 응답 생성 + public static ApiResponse onFailure(String code, String message, T data){ + return new ApiResponse<>(false, code, message, data); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/code/BaseCode.java b/sanho/spring/src/main/java/umc/spring/apipayload/code/BaseCode.java new file mode 100644 index 0000000..23ec249 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/code/BaseCode.java @@ -0,0 +1,8 @@ +package umc.spring.apipayload.code; + +public interface BaseCode { // SuccessStatus 코드를 위한 인터페이스 + + ReasonDTO getReason(); + + ReasonDTO getReasonHttpStatus(); +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/code/BaseErrorCode.java b/sanho/spring/src/main/java/umc/spring/apipayload/code/BaseErrorCode.java new file mode 100644 index 0000000..e172306 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/code/BaseErrorCode.java @@ -0,0 +1,8 @@ +package umc.spring.apipayload.code; + +public interface BaseErrorCode { // ErrorStatus 코드를 위한 인터페이스 + + ErrorReasonDTO getReason(); + + ErrorReasonDTO getReasonHttpStatus(); +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/code/ErrorReasonDTO.java b/sanho/spring/src/main/java/umc/spring/apipayload/code/ErrorReasonDTO.java new file mode 100644 index 0000000..f43e8e4 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/code/ErrorReasonDTO.java @@ -0,0 +1,18 @@ +package umc.spring.apipayload.code; + +import lombok.Builder; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@Builder +public class ErrorReasonDTO { // 에러 내용을 보여주는 Dto + + private HttpStatus httpStatus; + + private final boolean isSuccess; + private final String code; + private final String message; + + public boolean getIsSuccess() {return isSuccess;} +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/code/ReasonDTO.java b/sanho/spring/src/main/java/umc/spring/apipayload/code/ReasonDTO.java new file mode 100644 index 0000000..b4230dc --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/code/ReasonDTO.java @@ -0,0 +1,18 @@ +package umc.spring.apipayload.code; + +import lombok.Builder; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@Builder +public class ReasonDTO { // 성공 시 데이터 보여주는 Dto + + private HttpStatus httpStatus; + + private final boolean isSuccess; + private final String code; + private final String message; + + public boolean getIsSuccess(){return isSuccess;} +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/code/status/ErrorStatus.java b/sanho/spring/src/main/java/umc/spring/apipayload/code/status/ErrorStatus.java new file mode 100644 index 0000000..54cd6b8 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/code/status/ErrorStatus.java @@ -0,0 +1,75 @@ +package umc.spring.apipayload.code.status; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.code.ErrorReasonDTO; + +@Getter +@AllArgsConstructor +public enum ErrorStatus implements BaseErrorCode { // week8 미션 + + // 가장 일반적인 응답 + _INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON500", "서버 에러, 관리자에게 문의 바랍니다."), + _BAD_REQUEST(HttpStatus.BAD_REQUEST,"COMMON400","잘못된 요청입니다."), + _UNAUTHORIZED(HttpStatus.UNAUTHORIZED,"COMMON401","인증이 필요합니다."), + _FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON403", "금지된 요청입니다."), + + + // 멤버 관려 에러 + MEMBER_NOT_FOUND(HttpStatus.BAD_REQUEST, "MEMBER4001", "사용자가 없습니다."), + NICKNAME_NOT_EXIST(HttpStatus.BAD_REQUEST, "MEMBER4002", "닉네임은 필수 입니다."), + + // 예시,,, + ARTICLE_NOT_FOUND(HttpStatus.NOT_FOUND, "ARTICLE4001", "게시글이 없습니다."), + + // For test + TEMP_EXCEPTION(HttpStatus.BAD_REQUEST, "TEMP4001", "이거는 테스트"), + + // 음식 카테고리 관련 에러 + FOOD_CATEGORY_NOT_FOUND(HttpStatus.BAD_REQUEST, "FOODCATEGORY4001", "음식 카테고리가 없습니다."), + + // 지역 관련 에러 + REGION_NOT_FOUND(HttpStatus.BAD_REQUEST, "REGION4001", "지역이 없습니다."), + + // 가게 관련 에러 + STORE_NOT_FOUND(HttpStatus.BAD_REQUEST, "STORE4001", "가게가 없습니다."), + + // 미션 관련 에러 + Member_Mission_NOT_FOUND(HttpStatus.BAD_REQUEST, "MemberMission4001", "미션이 없습니다."), + + // 페이지 관련 에러 + PAGE_NOT_FOUND(HttpStatus.BAD_REQUEST, "page4001", "유효한 페이지가 없습니다."), + + // 미션 관련 에러 + MISSION_NOT_FOUND(HttpStatus.BAD_REQUEST, "mission4001", "해당 미션이 없습니다."), + MISSION_ALREADY_COMPLETE(HttpStatus.BAD_REQUEST, "mission4002", "이미 완료된 미션입니다."); + + + + + private final HttpStatus httpStatus; + private final String code; + private final String message; + + @Override + public ErrorReasonDTO getReason() { // enum에 등록된 에러 코드를 Dto의 형태로 보내주는 역할 + return ErrorReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(false) + .build(); + } + + @Override + public ErrorReasonDTO getReasonHttpStatus() { // GenereationException에서 쓰는데, 이 ErrorStatus의 message, code, isSuccss, httpStatus를 ErrorReasonDTO 형식에 맞게 보내줌 + return ErrorReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(false) + .httpStatus(httpStatus) + .build() + ; + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/code/status/SuccessStatus.java b/sanho/spring/src/main/java/umc/spring/apipayload/code/status/SuccessStatus.java new file mode 100644 index 0000000..19de481 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/code/status/SuccessStatus.java @@ -0,0 +1,38 @@ +package umc.spring.apipayload.code.status; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; +import umc.spring.apipayload.code.BaseCode; +import umc.spring.apipayload.code.ReasonDTO; + +@Getter +@AllArgsConstructor +public enum SuccessStatus implements BaseCode { + + // 일반적인 응답 + _OK(HttpStatus.OK, "COMMON200", "성공입니다."); // enum에서 선언하고 바로 초기화 + + private final HttpStatus httpStatus; + private final String code; + private final String message; + + @Override + public ReasonDTO getReason() { // of를 위한 코드 + return ReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(true) + .build(); + } + + @Override + public ReasonDTO getReasonHttpStatus() { // of를 위한 코드 - 이 Status의 message, code, isSuccess, httpStatus를 ReasonDTO 형식에 맞게 보내줌 + return ReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(true) + .httpStatus(httpStatus) + .build(); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/ExceptionAdvice.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/ExceptionAdvice.java new file mode 100644 index 0000000..add2804 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/ExceptionAdvice.java @@ -0,0 +1,125 @@ +package umc.spring.apipayload.exception; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import umc.spring.apipayload.ApiResponse; +import umc.spring.apipayload.code.ErrorReasonDTO; +import umc.spring.apipayload.code.status.ErrorStatus; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +@Slf4j +@RestControllerAdvice(annotations = {RestController.class}) +public class ExceptionAdvice extends ResponseEntityExceptionHandler { + + + @ExceptionHandler + public ResponseEntity validation(ConstraintViolationException e, WebRequest request) { + String errorMessage = e.getConstraintViolations().stream() + .map(constraintViolation -> constraintViolation.getMessage()) + .findFirst() + .orElseThrow(() -> new RuntimeException("ConstraintViolationException 추출 도중 에러 발생")); + + return handleExceptionInternalConstraint(e, ErrorStatus.valueOf(errorMessage), HttpHeaders.EMPTY,request); + } + + @Override + public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpHeaders headers, HttpStatusCode status, WebRequest request) { + + Map errors = new LinkedHashMap<>(); + + e.getBindingResult().getFieldErrors().stream() + .forEach(fieldError -> { + String fieldName = fieldError.getField(); + String errorMessage = Optional.ofNullable(fieldError.getDefaultMessage()).orElse(""); + errors.merge(fieldName, errorMessage, (existingErrorMessage, newErrorMessage) -> existingErrorMessage + ", " + newErrorMessage); + }); + + return handleExceptionInternalArgs(e,HttpHeaders.EMPTY,ErrorStatus.valueOf("_BAD_REQUEST"),request,errors); + } + + @ExceptionHandler + public ResponseEntity exception(Exception e, WebRequest request) { + e.printStackTrace(); + + return handleExceptionInternalFalse(e, ErrorStatus._INTERNAL_SERVER_ERROR, HttpHeaders.EMPTY, ErrorStatus._INTERNAL_SERVER_ERROR.getHttpStatus(),request, e.getMessage()); + } + + @ExceptionHandler(value = GeneralException.class) // GeneralException을 상속 받은 예외들도 다 처리가 됨 + public ResponseEntity onThrowException(GeneralException generalException, HttpServletRequest request) { + ErrorReasonDTO errorReasonHttpStatus = generalException.getErrorReasonHttpStatus(); + return handleExceptionInternal(generalException,errorReasonHttpStatus,null,request); + } + + private ResponseEntity handleExceptionInternal(Exception e, ErrorReasonDTO reason, + HttpHeaders headers, HttpServletRequest request) { // 여기서 발생한 예외에 대한 응답을 보냄. + + // 응답 본문 생성 + ApiResponse body = ApiResponse.onFailure(reason.getCode(),reason.getMessage(),null); +// e.printStackTrace(); + + + // 실제로 생성된 예외 응답을 클라이언트에게 반환하는 역할 + WebRequest webRequest = new ServletWebRequest(request); + return super.handleExceptionInternal( + e, + body, + headers, + reason.getHttpStatus(), + webRequest + ); + } + + private ResponseEntity handleExceptionInternalFalse(Exception e, ErrorStatus errorCommonStatus, + HttpHeaders headers, HttpStatus status, WebRequest request, String errorPoint) { + ApiResponse body = ApiResponse.onFailure(errorCommonStatus.getCode(),errorCommonStatus.getMessage(),errorPoint); + return super.handleExceptionInternal( + e, + body, + headers, + status, + request + ); + } + + private ResponseEntity handleExceptionInternalArgs(Exception e, HttpHeaders headers, ErrorStatus errorCommonStatus, + WebRequest request, Map errorArgs) { + ApiResponse body = ApiResponse.onFailure(errorCommonStatus.getCode(),errorCommonStatus.getMessage(),errorArgs); + return super.handleExceptionInternal( + e, + body, + headers, + errorCommonStatus.getHttpStatus(), + request + ); + } + + private ResponseEntity handleExceptionInternalConstraint(Exception e, ErrorStatus errorCommonStatus, + HttpHeaders headers, WebRequest request) { + ApiResponse body = ApiResponse.onFailure(errorCommonStatus.getCode(), errorCommonStatus.getMessage(), null); + return super.handleExceptionInternal( + e, + body, + headers, + errorCommonStatus.getHttpStatus(), + request + ); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/GeneralException.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/GeneralException.java new file mode 100644 index 0000000..94ad517 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/GeneralException.java @@ -0,0 +1,21 @@ +package umc.spring.apipayload.exception; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.code.ErrorReasonDTO; + +@Getter +@AllArgsConstructor +public class GeneralException extends RuntimeException { + + private BaseErrorCode code; // 이 code를 SuccessStatus가 구현하고, SuccessStatus에서 데이터를 가져온다. + + public ErrorReasonDTO getErrorReason() { + return this.code.getReason(); + } + + public ErrorReasonDTO getErrorReasonHttpStatus(){ // ErrorStatus에서 ErrorReasonDTO 형식으로 받아와서 ExceptionAdvice로 넘김 + return this.code.getReasonHttpStatus(); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/FoodCategoryHandler.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/FoodCategoryHandler.java new file mode 100644 index 0000000..906f80c --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/FoodCategoryHandler.java @@ -0,0 +1,10 @@ +package umc.spring.apipayload.exception.handler; + +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.exception.GeneralException; + +public class FoodCategoryHandler extends GeneralException { // week8 미션 + public FoodCategoryHandler(BaseErrorCode code) { + super(code); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MemberHandler.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MemberHandler.java new file mode 100644 index 0000000..9b7ce43 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MemberHandler.java @@ -0,0 +1,10 @@ +package umc.spring.apipayload.exception.handler; + +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.exception.GeneralException; + +public class MemberHandler extends GeneralException { // week8 미션 + public MemberHandler(BaseErrorCode code) { + super(code); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MemberMissionHandler.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MemberMissionHandler.java new file mode 100644 index 0000000..c7e1776 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MemberMissionHandler.java @@ -0,0 +1,10 @@ +package umc.spring.apipayload.exception.handler; + +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.exception.GeneralException; + +public class MemberMissionHandler extends GeneralException { // week8 미션 + public MemberMissionHandler(BaseErrorCode code) { + super(code); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MissionHandler.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MissionHandler.java new file mode 100644 index 0000000..9b959d7 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/MissionHandler.java @@ -0,0 +1,11 @@ +package umc.spring.apipayload.exception.handler; + +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.exception.GeneralException; + +public class MissionHandler extends GeneralException { // week8 미션 + + public MissionHandler(BaseErrorCode code) { + super(code); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/RegionHandler.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/RegionHandler.java new file mode 100644 index 0000000..d1dbe95 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/RegionHandler.java @@ -0,0 +1,11 @@ +package umc.spring.apipayload.exception.handler; + +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.exception.GeneralException; + +public class RegionHandler extends GeneralException { // week8 미션 + + public RegionHandler(BaseErrorCode code) { + super(code); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/StoreHandler.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/StoreHandler.java new file mode 100644 index 0000000..13c29c5 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/StoreHandler.java @@ -0,0 +1,10 @@ +package umc.spring.apipayload.exception.handler; + +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.exception.GeneralException; + +public class StoreHandler extends GeneralException { // week8 미션 + public StoreHandler(BaseErrorCode code) { + super(code); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/TempHandler.java b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/TempHandler.java new file mode 100644 index 0000000..746625a --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/apipayload/exception/handler/TempHandler.java @@ -0,0 +1,11 @@ +package umc.spring.apipayload.exception.handler; + +import umc.spring.apipayload.code.BaseErrorCode; +import umc.spring.apipayload.exception.GeneralException; + +public class TempHandler extends GeneralException { // GeneralException을 상속 받음. Exception 핸들링 예시. + + public TempHandler(BaseErrorCode errorCode) { // 에러 코드 ErrorStatus ex) ErrorStatus.TEMP_EXCEPTION + super(errorCode); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/config/QueryDSLConfig.java b/sanho/spring/src/main/java/umc/spring/config/QueryDSLConfig.java new file mode 100644 index 0000000..36da20e --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/config/QueryDSLConfig.java @@ -0,0 +1,19 @@ +package umc.spring.config; + +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@RequiredArgsConstructor +public class QueryDSLConfig { // JPAQueryFactory 를 Bean으로 등록 + + private final EntityManager entityManager; + + @Bean + public JPAQueryFactory jpaQueryFactory(){ + return new JPAQueryFactory(entityManager); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/config/SwaggerConfig.java b/sanho/spring/src/main/java/umc/spring/config/SwaggerConfig.java new file mode 100644 index 0000000..b409788 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/config/SwaggerConfig.java @@ -0,0 +1,41 @@ +package umc.spring.config; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SwaggerConfig { // week8 미션 + + @Bean + public OpenAPI UMCstudyAPI() { + Info info = new Info() + .title("UMC Server WorkBook API") + .description("UMC Server WorkBook API 명세서") + .version("1.0.0"); + + String jwtSchemeName = "JWT TOKEN"; + + // API 요청헤더에 인증정보 포함 + SecurityRequirement securityRequirement = new SecurityRequirement().addList(jwtSchemeName); + + // SecuritySchemes 등록 + Components components = new Components() + .addSecuritySchemes(jwtSchemeName, new SecurityScheme() + .name(jwtSchemeName) + .type(SecurityScheme.Type.HTTP) // HTTP 방식 + .scheme("bearer") + .bearerFormat("JWT")); + + return new OpenAPI() + .addServersItem(new Server().url("/")) + .info(info) + .addSecurityItem(securityRequirement) + .components(components); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/converter/MemberConverter.java b/sanho/spring/src/main/java/umc/spring/converter/MemberConverter.java new file mode 100644 index 0000000..cae009f --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/converter/MemberConverter.java @@ -0,0 +1,101 @@ +package umc.spring.converter; + +import org.springframework.data.domain.Page; +import umc.spring.domain.Member; +import umc.spring.domain.Mission; +import umc.spring.domain.Review; +import umc.spring.domain.enums.Gender; +import umc.spring.domain.enums.MissionStatus; +import umc.spring.domain.mapping.MemberMission; +import umc.spring.web.dto.MemberRequestDTO; +import umc.spring.web.dto.MemberResponseDTO; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class MemberConverter { // week8 미션 + + public static MemberResponseDTO.JoinResultDTO toJoinResultDTO(Member member){ + return MemberResponseDTO.JoinResultDTO.builder() + .memberId(member.getId()) + .createdAt(LocalDateTime.now()) + .build(); + } + + public static Member toMember(MemberRequestDTO.JoinDto request){ + + Gender gender = null; // 선택 안 했을 수도 있음 + + switch (request.getGender()){ + case 1: + gender = Gender.MALE; + break; + case 2: + gender = Gender.FEMALE; + break; + case 3: + gender = Gender.NONE; + break; + } + + return Member.builder() + .address(request.getAddress()) + .specAddress(request.getSpecAddress()) + .gender(gender) + .name(request.getName()) + .memberPreferList(new ArrayList<>()) + .build(); + } + + // week9 미션 - 특정 멤버 리뷰 조회 + public static MemberResponseDTO.MemberReviewDTO memberReviewDTO(Review review) { + return MemberResponseDTO.MemberReviewDTO.builder() + .ownerNickname(review.getMember().getName()) + .score(review.getScore()) + .body(review.getBody()) + .createdAt(review.getCreatedAt().toLocalDate()) + .build(); + } + + public static MemberResponseDTO.MemberReviewListDTO memberReviewListDTO(Page reviewPage) { + List memberReviewDTOList = reviewPage.stream() + .map(MemberConverter::memberReviewDTO).collect(Collectors.toList()); // 각각의 memberReviewDTO를 리스트에 넣어줌 + + return MemberResponseDTO.MemberReviewListDTO.builder() + .isLast(reviewPage.isLast()) + .isFirst(reviewPage.isFirst()) + .totalPage(reviewPage.getTotalPages()) + .totalElements(reviewPage.getTotalElements()) + .listSize(memberReviewDTOList.size()) + .reviewList(memberReviewDTOList) + .build(); + } + + // week9 미션 - 내가 진행 중인 미션 목록 + public static MemberResponseDTO.MemberMissionDTO memberMissionDTO(MemberMission memberMission) { + Mission mission = memberMission.getMission(); + + return MemberResponseDTO.MemberMissionDTO.builder() + .storeName(mission.getStore().getName()) + .missionSpec(mission.getMissionSpec()) + .reward(mission.getReward()) + .status(MissionStatus.CHALLENGING) // 진행 중인 미션으로 하드 코딩 + .build(); + } + + public static MemberResponseDTO.MemberMissionListDTO memberMissionListDTO(Page memberMissionPage) { + List memberMissionDTOList = memberMissionPage.stream() + .map(MemberConverter::memberMissionDTO).collect(Collectors.toList()); + + return MemberResponseDTO.MemberMissionListDTO.builder() + .isLast(memberMissionPage.isLast()) + .isFirst(memberMissionPage.isFirst()) + .totalPage(memberMissionPage.getTotalPages()) + .totalElements(memberMissionPage.getTotalElements()) + .listSize(memberMissionDTOList.size()) + .missionList(memberMissionDTOList) + .build(); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/converter/MemberPreferConverter.java b/sanho/spring/src/main/java/umc/spring/converter/MemberPreferConverter.java new file mode 100644 index 0000000..0ee0945 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/converter/MemberPreferConverter.java @@ -0,0 +1,20 @@ +package umc.spring.converter; + +import umc.spring.domain.FoodCategory; +import umc.spring.domain.mapping.MemberPrefer; + +import java.util.List; +import java.util.stream.Collectors; + +public class MemberPreferConverter { // week8 미션 + + public static List toMemberPreferList(List foodCategoryList){ + + return foodCategoryList.stream() + .map(foodCategory -> + MemberPrefer.builder() + .foodCategory(foodCategory) + .build() + ).collect(Collectors.toList()); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/converter/MissionConverter.java b/sanho/spring/src/main/java/umc/spring/converter/MissionConverter.java new file mode 100644 index 0000000..5d11b3b --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/converter/MissionConverter.java @@ -0,0 +1,45 @@ +package umc.spring.converter; + +import umc.spring.domain.Mission; +import umc.spring.domain.Store; +import umc.spring.domain.mapping.MemberMission; +import umc.spring.web.dto.MissionRequestDTO; +import umc.spring.web.dto.MissionResponseDTO; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + + +public class MissionConverter { // week8 미션 + + public static MissionResponseDTO.AddMissionResultDTO toAddMissionDTO(Mission mission){ + return MissionResponseDTO.AddMissionResultDTO.builder() + .missionId(mission.getId()) + .createdAt(LocalDateTime.now()) + .build(); + } + + public static Mission toMission(MissionRequestDTO.AddMissionDTO request, Store store, List memberMissionList) { + + return Mission.builder() + .reward(request.getReward()) + .deadline(request.getDeadline()) + .missionSpec(request.getMissionSpec()) + .store(store) + .memberMissionList(memberMissionList) + .build(); + } + + // week9 미션 - 진행 중인 미션을 진행 완료로 수정하기 + public static MissionResponseDTO.MemberMissionDTO memberMissionDTO(MemberMission memberMission) { + Mission mission = memberMission.getMission(); + + return MissionResponseDTO.MemberMissionDTO.builder() + .memberName(memberMission.getMember().getName()) + .missionSpec(mission.getMissionSpec()) + .reward(mission.getReward()) + .status(memberMission.getStatus()) + .build(); + } + +} diff --git a/sanho/spring/src/main/java/umc/spring/converter/ReviewConverter.java b/sanho/spring/src/main/java/umc/spring/converter/ReviewConverter.java new file mode 100644 index 0000000..48b6c4f --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/converter/ReviewConverter.java @@ -0,0 +1,30 @@ +package umc.spring.converter; + +import umc.spring.domain.Member; +import umc.spring.domain.Review; +import umc.spring.domain.Store; +import umc.spring.web.dto.ReviewRequestDTO; +import umc.spring.web.dto.ReviewResponseDTO; +import java.time.LocalDateTime; + + +public class ReviewConverter { // week8 미션 + + public static ReviewResponseDTO.AddReviewResultDTO toAddResultDTO(Review review){ + return ReviewResponseDTO.AddReviewResultDTO.builder() + .reviewId(review.getId()) + .createdAt(LocalDateTime.now()) + .build(); + } + + public static Review toReview(ReviewRequestDTO.AddReviewDto request, Member member, Store store){ + + return Review.builder() + .title(request.getTitle()) + .body(request.getBody()) + .score(request.getScore()) + .member(member) + .store(store) + .build(); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/converter/StoreConverter.java b/sanho/spring/src/main/java/umc/spring/converter/StoreConverter.java new file mode 100644 index 0000000..6ca7171 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/converter/StoreConverter.java @@ -0,0 +1,83 @@ +package umc.spring.converter; + +import org.springframework.data.domain.Page; +import umc.spring.domain.Mission; +import umc.spring.domain.Region; +import umc.spring.domain.Review; +import umc.spring.domain.Store; +import umc.spring.web.dto.StoreRequestDTO; +import umc.spring.web.dto.StoreResponseDTO; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + + +public class StoreConverter { // week8 미션 + + public static StoreResponseDTO.AddStoreDTO toAddResultDTO(Store store){ + return StoreResponseDTO.AddStoreDTO.builder() + .storeId(store.getId()) + .createdAt(LocalDateTime.now()) + .build(); + } + + public static Store toStore(StoreRequestDTO.AddStoreDto request, Region region){ // name, address, region + + return Store.builder() + .name(request.getName()) + .address(request.getAddress()) + .region(region) + .reviewList(new ArrayList<>()) + .build(); + } + + // week9 코드 - 리뷰 목록 조회 + public static StoreResponseDTO.ReviewPreViewDTO reviewPreViewDTO(Review review){ // 해당 가게 각각의 리뷰 DTO + return StoreResponseDTO.ReviewPreViewDTO.builder() + .ownerNickname(review.getMember().getName()) + .score(review.getScore()) + .createdAt(review.getCreatedAt().toLocalDate()) + .body(review.getBody()) + .build(); + } + + public static StoreResponseDTO.ReviewPreViewListDTO reviewPreViewListDTO(Page reviewPage){ // 위 DTO를 java stream으로 변환된 각각의 DTO를 List에 넣어줌 + List reviewPreViewDTOList = reviewPage.stream() + .map(StoreConverter::reviewPreViewDTO).collect(Collectors.toList()); + + return StoreResponseDTO.ReviewPreViewListDTO.builder() + .isLast(reviewPage.isLast()) + .isFirst(reviewPage.isFirst()) + .totalPage(reviewPage.getTotalPages()) + .totalElements(reviewPage.getTotalElements()) + .listSize(reviewPreViewDTOList.size()) + .reviewList(reviewPreViewDTOList) + .build(); + } + + // week9 미션 - 특정 가게 미션 목록 조회 + public static StoreResponseDTO.StoreMissionDTO storeMissionDTO(Mission mission) { + return StoreResponseDTO.StoreMissionDTO.builder() + .storeName(mission.getStore().getName()) + .missionSpec(mission.getMissionSpec()) + .reward(mission.getReward()) + .createdAt(mission.getCreatedAt().toLocalDate()) + .build(); + } + + public static StoreResponseDTO.StoreMissionListDTO storeMissionListDTO(Page missionPage) { + List storeMissionDTOList = missionPage.stream() + .map(StoreConverter::storeMissionDTO).collect(Collectors.toList()); + + return StoreResponseDTO.StoreMissionListDTO.builder() + .isLast(missionPage.isLast()) + .isFirst(missionPage.isFirst()) + .totalPage(missionPage.getTotalPages()) + .totalElements(missionPage.getTotalElements()) + .listSize(storeMissionDTOList.size()) + .missionList(storeMissionDTOList) + .build(); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/converter/TempConverter.java b/sanho/spring/src/main/java/umc/spring/converter/TempConverter.java new file mode 100644 index 0000000..8dd2fc3 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/converter/TempConverter.java @@ -0,0 +1,18 @@ +package umc.spring.converter; + +import umc.spring.web.dto.TempResponse; + +public class TempConverter { // TempResponse.TempTestDTO의 형태로 바꿔주는 역할 + + public static TempResponse.TempTestDTO toTempTestDTO(){ // static으로 선언 + return TempResponse.TempTestDTO.builder() // 응답도 builder 패턴으로 생성 + .testString("This is Test!") // 이게 result 값 + .build(); + } + + public static TempResponse.TempExceptionDTO toTempExceptionDTO(Integer flag){ + return TempResponse.TempExceptionDTO.builder() + .flag(flag) + .build(); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/FoodCategory.java b/sanho/spring/src/main/java/umc/spring/domain/FoodCategory.java new file mode 100644 index 0000000..9e4773b --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/FoodCategory.java @@ -0,0 +1,22 @@ +package umc.spring.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class FoodCategory extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 15) + private String name; + + +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/Member.java b/sanho/spring/src/main/java/umc/spring/domain/Member.java new file mode 100644 index 0000000..e181b78 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/Member.java @@ -0,0 +1,91 @@ +package umc.spring.domain; + +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.ColumnDefault; +import org.hibernate.annotations.DynamicInsert; +import org.hibernate.annotations.DynamicUpdate; +import umc.spring.domain.common.BaseEntity; +import umc.spring.domain.enums.Gender; +import umc.spring.domain.enums.MemberStatus; +import umc.spring.domain.enums.SocialType; +import umc.spring.domain.mapping.MemberAgree; +import umc.spring.domain.mapping.MemberMission; +import umc.spring.domain.mapping.MemberPrefer; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +@Entity // JPA의 엔티티 +@Getter +@DynamicUpdate +@DynamicInsert +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Member extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) // JPA가 통신하는 DBMS의 방식을 따른다. - Mysql + private Long id; + + @Column(nullable = false, length = 20) // 널 값 허용하지 않음 + private String name; + +// @Column(columnDefinition = "VARCHAR(20)") // 널 값 허용 +// private String name; + + @Column(nullable = false, length = 40) + private String address; + + @Column(nullable = false, length = 40) + private String specAddress; + + @Enumerated(EnumType.STRING) + @Column(columnDefinition = "VARCHAR(10)") + private Gender gender; + + @Enumerated(EnumType.STRING) + private SocialType socialType; + + @Enumerated(EnumType.STRING) + @Column(columnDefinition = "VARCHAR(15) DEFAULT 'ACTIVE'") + private MemberStatus status; + + @Column(columnDefinition = "DATETIME") + private LocalDate inactiveDate; + +// @Column(nullable = false, length = 50) + private String email; + + @ColumnDefault("0") + private Integer point; + + // 나이 추가 + private Integer age; + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) // CascadeType.ALL로 인해 persist(member) 하면 아래 4개도 같이 persist 됨. + private List memberAgreeList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + private List memberPreferList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + private List reviewList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + private List memberMissionList = new ArrayList<>(); +} + +/** + * 정리 + * 1. 각 도메인 다 만들기 + * 이 때 created_at과 updated_at은 BaseEntity로 빼고 상속 받기, Application에 @EnableJpaAuditing도 넣어줘야되 + * 2. 매핑 테이블 만들기 + * 3. 연관관계 매핑 @ManyToOne (단방향 매핑) - FK 갖는 연관관계 주인 기준 + * ex) @ManyToOne, @JoinColumn + * 4. 연관관계 매핑 @OneToMany (양방향 매핑) - 수정/삭제 많이 안 하는 엔티티는 양방향 설정 안 해도 됨. - 연관관계 주인 반대 + * @ManyToOne 한 것을 @OneToMany로 받아야 됨. + * 5. 칼럼 별 세부적 설정 @Column + * */ \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/Mission.java b/sanho/spring/src/main/java/umc/spring/domain/Mission.java new file mode 100644 index 0000000..a221e26 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/Mission.java @@ -0,0 +1,49 @@ +package umc.spring.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.common.BaseEntity; +import umc.spring.domain.mapping.MemberMission; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Mission extends BaseEntity { // week8 미션 + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Integer reward; + + @Column(columnDefinition = "DATETIME") // LocalDate는 기본으로 DATE로 바뀜 + private LocalDate deadline; + + @Column(columnDefinition = "TEXT") + private String missionSpec; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + + @OneToMany(mappedBy = "mission", cascade = CascadeType.ALL) + private List memberMissionList = new ArrayList<>(); + + //==연관관계 메서드==// + public void setStore(Store store) { + this.store = store; + store.getMisisonList().add(this); + } + + public void setMemberMissionList(MemberMission memberMission) { + this.memberMissionList.add(memberMission); + memberMission.setMission(this); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/Region.java b/sanho/spring/src/main/java/umc/spring/domain/Region.java new file mode 100644 index 0000000..0ce35d6 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/Region.java @@ -0,0 +1,26 @@ +package umc.spring.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.common.BaseEntity; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Region extends BaseEntity { // week8 미션 + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 20) + private String name; + + @OneToMany(mappedBy = "region", cascade = CascadeType.ALL) + private List storeList = new ArrayList<>(); +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/Review.java b/sanho/spring/src/main/java/umc/spring/domain/Review.java new file mode 100644 index 0000000..260f891 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/Review.java @@ -0,0 +1,42 @@ +package umc.spring.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Review extends BaseEntity { // week8 미션 + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String title; + + private String body; + + private Float score; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + //==연관관계 메서드==// + public void setMember(Member member) { + this.member = member; + member.getReviewList().add(this); + } + + public void setStore(Store store) { + this.store = store; + store.getReviewList().add(this); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/Store.java b/sanho/spring/src/main/java/umc/spring/domain/Store.java new file mode 100644 index 0000000..8af8c48 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/Store.java @@ -0,0 +1,56 @@ +package umc.spring.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.common.BaseEntity; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Store extends BaseEntity { // week8 미션 + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 50) + private String name; + + @Column(nullable = false, length = 50) + private String address; + + private Float score; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "region_id") + private Region region; + + @OneToMany(mappedBy = "store", cascade = CascadeType.ALL) + private List reviewList = new ArrayList<>(); + + @OneToMany(mappedBy = "store", cascade = CascadeType.ALL) + private List misisonList = new ArrayList<>(); + + //==연관관계 메서드==// + public void setRegion(Region region) { + this.region = region; + region.getStoreList().add(this); + } + + + @Override + public String toString() { + return "Store{" + + "id=" + id + + ", name='" + name + '\'' + + ", address='" + address + '\'' + + ", score=" + score + + ", region=" + (region != null ? region.getName() : "N/A") + // region의 이름 출력 + '}'; + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/Terms.java b/sanho/spring/src/main/java/umc/spring/domain/Terms.java new file mode 100644 index 0000000..25fb0be --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/Terms.java @@ -0,0 +1,32 @@ +package umc.spring.domain; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.common.BaseEntity; +import umc.spring.domain.mapping.MemberAgree; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Terms extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 20) + private String title; + + @Column(columnDefinition = "TEXT") + private String body; + + private Boolean optional; + + @OneToMany(mappedBy = "terms", cascade = CascadeType.ALL) + private List memberAgreeList = new ArrayList<>(); +} diff --git a/sanho/spring/src/main/java/umc/spring/domain/common/BaseEntity.java b/sanho/spring/src/main/java/umc/spring/domain/common/BaseEntity.java new file mode 100644 index 0000000..c6e6249 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/common/BaseEntity.java @@ -0,0 +1,25 @@ +package umc.spring.domain.common; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@Getter +public abstract class BaseEntity { + + @CreatedDate + @Column(columnDefinition = "DATETIME(6)") + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(columnDefinition = "DATETIME(6)") + private LocalDateTime updatedAt; +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/enums/Gender.java b/sanho/spring/src/main/java/umc/spring/domain/enums/Gender.java new file mode 100644 index 0000000..81b604b --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/enums/Gender.java @@ -0,0 +1,5 @@ +package umc.spring.domain.enums; + +public enum Gender { + MALE, FEMALE, NONE; +} diff --git a/sanho/spring/src/main/java/umc/spring/domain/enums/MemberStatus.java b/sanho/spring/src/main/java/umc/spring/domain/enums/MemberStatus.java new file mode 100644 index 0000000..3a2959f --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/enums/MemberStatus.java @@ -0,0 +1,5 @@ +package umc.spring.domain.enums; + +public enum MemberStatus { + ACTIVE, INACTIVE; +} diff --git a/sanho/spring/src/main/java/umc/spring/domain/enums/MissionStatus.java b/sanho/spring/src/main/java/umc/spring/domain/enums/MissionStatus.java new file mode 100644 index 0000000..b481036 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/enums/MissionStatus.java @@ -0,0 +1,5 @@ +package umc.spring.domain.enums; + +public enum MissionStatus { + CHALLENGING, COMPLETE; +} diff --git a/sanho/spring/src/main/java/umc/spring/domain/enums/SocialType.java b/sanho/spring/src/main/java/umc/spring/domain/enums/SocialType.java new file mode 100644 index 0000000..a73078e --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/enums/SocialType.java @@ -0,0 +1,5 @@ +package umc.spring.domain.enums; + +public enum SocialType { + KAKAO, GOOGLE, NAVER, APPLE; +} diff --git a/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberAgree.java b/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberAgree.java new file mode 100644 index 0000000..8a34132 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberAgree.java @@ -0,0 +1,27 @@ +package umc.spring.domain.mapping; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.Member; +import umc.spring.domain.Terms; +import umc.spring.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class MemberAgree extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "terms_id") + private Terms terms; +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberMission.java b/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberMission.java new file mode 100644 index 0000000..86e4459 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberMission.java @@ -0,0 +1,33 @@ +package umc.spring.domain.mapping; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.Member; +import umc.spring.domain.Mission; +import umc.spring.domain.common.BaseEntity; +import umc.spring.domain.enums.MissionStatus; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class MemberMission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 15) + private MissionStatus status; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "mission_id") + private Mission mission; +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberPrefer.java b/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberPrefer.java new file mode 100644 index 0000000..a846d7a --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/domain/mapping/MemberPrefer.java @@ -0,0 +1,40 @@ +package umc.spring.domain.mapping; + +import jakarta.persistence.*; +import lombok.*; +import umc.spring.domain.FoodCategory; +import umc.spring.domain.Member; +import umc.spring.domain.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class MemberPrefer extends BaseEntity { // week8 미션 + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) // 지연 로딩 + @JoinColumn(name = "member_id") // FK 이름 + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "category_id") + private FoodCategory foodCategory; + + + //==연관관계 메서드==// + public void setMember(Member member){ + if(this.member != null) + member.getMemberPreferList().remove(this); + this.member = member; + member.getMemberPreferList().add(this); + } + + public void setFoodCategory(FoodCategory foodCategory){ + this.foodCategory = foodCategory; + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/repository/foodcategory/FoodCategoryRepository.java b/sanho/spring/src/main/java/umc/spring/repository/foodcategory/FoodCategoryRepository.java new file mode 100644 index 0000000..7397bfe --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/foodcategory/FoodCategoryRepository.java @@ -0,0 +1,7 @@ +package umc.spring.repository.foodcategory; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.spring.domain.FoodCategory; + +public interface FoodCategoryRepository extends JpaRepository { // week8 미션 +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/repository/member/MemberRepository.java b/sanho/spring/src/main/java/umc/spring/repository/member/MemberRepository.java new file mode 100644 index 0000000..4ef62d5 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/member/MemberRepository.java @@ -0,0 +1,7 @@ +package umc.spring.repository.member; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.spring.domain.Member; + +public interface MemberRepository extends JpaRepository { // week8 미션 +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/repository/membermission/MemberMissionRepository.java b/sanho/spring/src/main/java/umc/spring/repository/membermission/MemberMissionRepository.java new file mode 100644 index 0000000..10fd466 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/membermission/MemberMissionRepository.java @@ -0,0 +1,17 @@ +package umc.spring.repository.membermission; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.jpa.repository.JpaRepository; +import umc.spring.domain.Member; +import umc.spring.domain.Mission; +import umc.spring.domain.mapping.MemberMission; + +public interface MemberMissionRepository extends JpaRepository { // week8 미션 + + // week9 미션 - 내가 진행 중인 미션 목록 + Page findAllByMember(Member member, PageRequest pageRequest); + + // week9 미션 - 진행 중인 미션을 진행 완료로 수정하기 + MemberMission findByMission(Mission mission); +} diff --git a/sanho/spring/src/main/java/umc/spring/repository/mission/MissionRepository.java b/sanho/spring/src/main/java/umc/spring/repository/mission/MissionRepository.java new file mode 100644 index 0000000..d87c0ad --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/mission/MissionRepository.java @@ -0,0 +1,16 @@ +package umc.spring.repository.mission; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.jpa.repository.JpaRepository; +import umc.spring.domain.Mission; +import umc.spring.domain.Store; +import umc.spring.domain.mapping.MemberMission; + +import java.util.List; + +public interface MissionRepository extends JpaRepository { // week8 미션 + + // week9 미션 - 특정 가게 미션 목록 조회 + Page findAllByStore(Store store, PageRequest pageRequest); // store를 통해 미션 목록을 가져감 +} diff --git a/sanho/spring/src/main/java/umc/spring/repository/region/RegionRepository.java b/sanho/spring/src/main/java/umc/spring/repository/region/RegionRepository.java new file mode 100644 index 0000000..c3101be --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/region/RegionRepository.java @@ -0,0 +1,7 @@ +package umc.spring.repository.region; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.spring.domain.Region; + +public interface RegionRepository extends JpaRepository { // week8 미션 +} diff --git a/sanho/spring/src/main/java/umc/spring/repository/review/ReviewRepository.java b/sanho/spring/src/main/java/umc/spring/repository/review/ReviewRepository.java new file mode 100644 index 0000000..32a3388 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/review/ReviewRepository.java @@ -0,0 +1,16 @@ +package umc.spring.repository.review; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.jpa.repository.JpaRepository; +import umc.spring.domain.Member; +import umc.spring.domain.Review; +import umc.spring.domain.Store; + +public interface ReviewRepository extends JpaRepository { // week8 미션 + + Page findAllByStore(Store store, PageRequest pageRequest); // PageRequest는 페이징과 관련된 옵션이 포함 + + // week9 미션 - 특정 멤버 리뷰 조회 + Page findAllByMember(Member member, PageRequest pageRequest); +} diff --git a/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepository.java b/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepository.java new file mode 100644 index 0000000..5151d83 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepository.java @@ -0,0 +1,7 @@ +package umc.spring.repository.store; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.spring.domain.Store; + +public interface StoreRepository extends JpaRepository, StoreRepositoryCustom { // 구현이 아닌 단순 확장이라 extends +} diff --git a/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepositoryCustom.java b/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepositoryCustom.java new file mode 100644 index 0000000..94dac34 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepositoryCustom.java @@ -0,0 +1,9 @@ +package umc.spring.repository.store; + +import umc.spring.domain.Store; + +import java.util.List; + +public interface StoreRepositoryCustom { + List dynamicQueryWithBooleanBuilder(String name, Float score); +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepositoryImpl.java b/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepositoryImpl.java new file mode 100644 index 0000000..6a47b8b --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/repository/store/StoreRepositoryImpl.java @@ -0,0 +1,43 @@ +package umc.spring.repository.store; + +import com.querydsl.core.BooleanBuilder; +import com.querydsl.jpa.impl.JPAQueryFactory; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; +import umc.spring.domain.QStore; +import umc.spring.domain.Store; + +import java.util.List; + +@Repository +@RequiredArgsConstructor +public class StoreRepositoryImpl implements StoreRepositoryCustom{ + + private final JPAQueryFactory jpaQueryFactory; + private final QStore store = QStore.store; + + @Override + public List dynamicQueryWithBooleanBuilder(String name, Float score) { + BooleanBuilder predicate = new BooleanBuilder(); // 동적 쿼리 작성 BooleanBuilder + + if (name != null) { + predicate.and(store.name.eq(name)); // equal + } + + if (score != null) { + predicate.and(store.score.goe(4.0f)); // "greater than or equal to" + } + + // 가게 이름이 name이고, 평점이 4.0보다 크거나 같은 가게 + return jpaQueryFactory + .selectFrom(store) + .where(predicate) + .fetch(); + + +// List fetch = jpaQueryFactory +// .selectFrom(store) +// .where(store.name.eq(name), store.score.goe(4.0f)) +// .fetch(); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/service/member/MemberCommandService.java b/sanho/spring/src/main/java/umc/spring/service/member/MemberCommandService.java new file mode 100644 index 0000000..47ffc37 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/member/MemberCommandService.java @@ -0,0 +1,9 @@ +package umc.spring.service.member; + +import umc.spring.domain.Member; +import umc.spring.web.dto.MemberRequestDTO; + +public interface MemberCommandService { // week8 미션 + + Member joinMember(MemberRequestDTO.JoinDto request); +} diff --git a/sanho/spring/src/main/java/umc/spring/service/member/MemberCommandServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/member/MemberCommandServiceImpl.java new file mode 100644 index 0000000..f692e4f --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/member/MemberCommandServiceImpl.java @@ -0,0 +1,47 @@ +package umc.spring.service.member; + +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.apipayload.exception.handler.FoodCategoryHandler; +import umc.spring.converter.MemberConverter; +import umc.spring.converter.MemberPreferConverter; +import umc.spring.domain.FoodCategory; +import umc.spring.domain.Member; +import umc.spring.domain.mapping.MemberPrefer; +import umc.spring.repository.foodcategory.FoodCategoryRepository; +import umc.spring.repository.member.MemberRepository; +import umc.spring.web.dto.MemberRequestDTO; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class MemberCommandServiceImpl implements MemberCommandService{ // week8 미션 + + private final MemberRepository memberRepository; + + private final FoodCategoryRepository foodCategoryRepository; + + @Override + @Transactional + public Member joinMember(MemberRequestDTO.JoinDto request) { + + Member newMember = MemberConverter.toMember(request); + +// List preferCategory = request.getPreferCategory(); + + List foodCategoryList = request.getPreferCategory().stream() + .map(category -> { + return foodCategoryRepository.findById(category).orElseThrow(() -> new FoodCategoryHandler(ErrorStatus.FOOD_CATEGORY_NOT_FOUND)); + }).collect(Collectors.toList()); + + List memberPreferList = MemberPreferConverter.toMemberPreferList(foodCategoryList); + + memberPreferList.forEach(memberPrefer -> {memberPrefer.setMember(newMember);}); + + return memberRepository.save(newMember); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/service/member/MemberQueryService.java b/sanho/spring/src/main/java/umc/spring/service/member/MemberQueryService.java new file mode 100644 index 0000000..125e9e3 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/member/MemberQueryService.java @@ -0,0 +1,15 @@ +package umc.spring.service.member; + +import org.springframework.data.domain.Page; +import umc.spring.domain.Mission; +import umc.spring.domain.Review; +import umc.spring.domain.mapping.MemberMission; + +public interface MemberQueryService { + + // week9 미션 + Page getReviewList(Long memberId, Integer page); // Page 자체에 페이징과 관련된 여러 정보가 담김 -> Paging을 위한 추상화 제공 + + // week9 미션 - 내가 진행 중인 미션 목록 + Page getMemberMissionList(Long memberId, Integer page); +} diff --git a/sanho/spring/src/main/java/umc/spring/service/member/MemberQueryServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/member/MemberQueryServiceImpl.java new file mode 100644 index 0000000..68a0a72 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/member/MemberQueryServiceImpl.java @@ -0,0 +1,43 @@ +package umc.spring.service.member; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import umc.spring.domain.Member; +import umc.spring.domain.Review; +import umc.spring.domain.mapping.MemberMission; +import umc.spring.repository.member.MemberRepository; +import umc.spring.repository.membermission.MemberMissionRepository; +import umc.spring.repository.mission.MissionRepository; +import umc.spring.repository.review.ReviewRepository; + + +@Service +@RequiredArgsConstructor +public class MemberQueryServiceImpl implements MemberQueryService{ + + private final MemberRepository memberRepository; + private final ReviewRepository reviewRepository; + private final MissionRepository missionRepository; + private final MemberMissionRepository memberMissionRepository; + + // week9 미션 - 특정 멤버 리뷰 조회 + @Override + public Page getReviewList(Long memberId, Integer page) { + Member member = memberRepository.findById(memberId).get(); // .get()을 안 붙이면 Optional + + Page reviewPage = reviewRepository.findAllByMember(member, PageRequest.of(page, 10)); + + return reviewPage; + } + + // week9 미션 - 내가 진행 중인 미션 목록 + + @Override + public Page getMemberMissionList(Long memberId, Integer page) { + Member member = memberRepository.findById(memberId).get(); + + return memberMissionRepository.findAllByMember(member, PageRequest.of(page, 10)); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/service/mission/MissionCommandService.java b/sanho/spring/src/main/java/umc/spring/service/mission/MissionCommandService.java new file mode 100644 index 0000000..e67aeae --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/mission/MissionCommandService.java @@ -0,0 +1,9 @@ +package umc.spring.service.mission; + +import umc.spring.domain.Mission; +import umc.spring.web.dto.MissionRequestDTO; + +public interface MissionCommandService { // week8 미션 + + Mission addMission(MissionRequestDTO.AddMissionDTO request); +} diff --git a/sanho/spring/src/main/java/umc/spring/service/mission/MissionCommandServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/mission/MissionCommandServiceImpl.java new file mode 100644 index 0000000..cf5d9a6 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/mission/MissionCommandServiceImpl.java @@ -0,0 +1,53 @@ +package umc.spring.service.mission; + +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.apipayload.exception.handler.*; +import umc.spring.converter.MissionConverter; +import umc.spring.domain.*; +import umc.spring.domain.mapping.MemberMission; +import umc.spring.repository.membermission.MemberMissionRepository; +import umc.spring.repository.mission.MissionRepository; +import umc.spring.repository.store.StoreRepository; +import umc.spring.web.dto.MissionRequestDTO; +import java.util.ArrayList; +import java.util.List; + + +@Service +@RequiredArgsConstructor +public class MissionCommandServiceImpl implements MissionCommandService { + + private final MissionRepository missionRepository; + private final StoreRepository storeRepository; + private final MemberMissionRepository memberMissionRepository; + private List memberMissionList = new ArrayList<>(); // 리스트를 필드로 유지 + + + @Override + @Transactional + public Mission addMission(MissionRequestDTO.AddMissionDTO request) { // week8 미션 + + Store store = storeRepository.findById(request.getStoreId()) + .orElseThrow(() -> new MissionHandler(ErrorStatus.MEMBER_NOT_FOUND)); + + MemberMission memberMission = memberMissionRepository.findById(request.getMemberMissionId()) + .orElseThrow(() -> new MemberMissionHandler(ErrorStatus.Member_Mission_NOT_FOUND)); + + // 첫 번째 요청에서는 리스트를 생성, 이후에는 기존 리스트에 추가 + if (memberMissionList == null) { + memberMissionList = new ArrayList<>(); + } + memberMissionList.add(memberMission); // memberMission 추가 + + + Mission newMission = MissionConverter.toMission(request, store, memberMissionList); + + newMission.setStore(store); + newMission.setMemberMissionList(memberMission); + + return missionRepository.save(newMission); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/service/mission/MissionQueryService.java b/sanho/spring/src/main/java/umc/spring/service/mission/MissionQueryService.java new file mode 100644 index 0000000..d53e875 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/mission/MissionQueryService.java @@ -0,0 +1,9 @@ +package umc.spring.service.mission; + +import umc.spring.domain.mapping.MemberMission; + +public interface MissionQueryService { + MemberMission findMemberMission(Long missionId); + + void completeMission(MemberMission memberMission); +} diff --git a/sanho/spring/src/main/java/umc/spring/service/mission/MissionQueryServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/mission/MissionQueryServiceImpl.java new file mode 100644 index 0000000..5ef542e --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/mission/MissionQueryServiceImpl.java @@ -0,0 +1,39 @@ +package umc.spring.service.mission; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.apipayload.exception.handler.MemberMissionHandler; +import umc.spring.domain.Mission; +import umc.spring.domain.enums.MissionStatus; +import umc.spring.domain.mapping.MemberMission; +import umc.spring.repository.membermission.MemberMissionRepository; +import umc.spring.repository.mission.MissionRepository; + +@Service +@RequiredArgsConstructor +public class MissionQueryServiceImpl implements MissionQueryService { + + private final MissionRepository missionRepository; + private final MemberMissionRepository memberMissionRepository; + + @Override + public MemberMission findMemberMission(Long missionId) { + Mission mission = missionRepository.findById(missionId).get(); + MemberMission memberMission = memberMissionRepository.findByMission(mission); + + return memberMission; + } + + @Override + @Transactional + public void completeMission(MemberMission memberMission) { + // 미션 상태가 COMPLETE면 예외 터뜨리기 + if (memberMission.getStatus() == MissionStatus.COMPLETE) { + throw new MemberMissionHandler(ErrorStatus.MISSION_ALREADY_COMPLETE); + } + + memberMission.setStatus(MissionStatus.COMPLETE); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/service/review/ReviewCommandService.java b/sanho/spring/src/main/java/umc/spring/service/review/ReviewCommandService.java new file mode 100644 index 0000000..e144409 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/review/ReviewCommandService.java @@ -0,0 +1,9 @@ +package umc.spring.service.review; + +import umc.spring.domain.Review; +import umc.spring.web.dto.ReviewRequestDTO; + +public interface ReviewCommandService { + + Review addReview(ReviewRequestDTO.AddReviewDto request); // week8 미션 +} diff --git a/sanho/spring/src/main/java/umc/spring/service/review/ReviewCommandServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/review/ReviewCommandServiceImpl.java new file mode 100644 index 0000000..059b438 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/review/ReviewCommandServiceImpl.java @@ -0,0 +1,43 @@ +package umc.spring.service.review; + +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.apipayload.exception.handler.MemberHandler; +import umc.spring.apipayload.exception.handler.StoreHandler; +import umc.spring.converter.ReviewConverter; +import umc.spring.domain.Member; +import umc.spring.domain.Review; +import umc.spring.domain.Store; +import umc.spring.repository.member.MemberRepository; +import umc.spring.repository.review.ReviewRepository; +import umc.spring.repository.store.StoreRepository; +import umc.spring.web.dto.ReviewRequestDTO; + +@Service +@RequiredArgsConstructor +public class ReviewCommandServiceImpl implements ReviewCommandService { // week8 미션 + + private final ReviewRepository reviewRepository; + private final MemberRepository memberRepository; + private final StoreRepository storeRepository; + + @Override + @Transactional + public Review addReview(ReviewRequestDTO.AddReviewDto request) { + + Member member = memberRepository.findById(request.getMemberId()) + .orElseThrow(() -> new MemberHandler(ErrorStatus.MEMBER_NOT_FOUND)); + + Store store = storeRepository.findById(request.getStoreId()) + .orElseThrow(() -> new StoreHandler(ErrorStatus.STORE_NOT_FOUND)); + + Review newReview = ReviewConverter.toReview(request, member, store); + + newReview.setMember(member); + newReview.setStore(store); + + return reviewRepository.save(newReview); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/service/store/StoreCommandService.java b/sanho/spring/src/main/java/umc/spring/service/store/StoreCommandService.java new file mode 100644 index 0000000..3cc1444 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/store/StoreCommandService.java @@ -0,0 +1,9 @@ +package umc.spring.service.store; + +import umc.spring.domain.Store; +import umc.spring.web.dto.StoreRequestDTO; + +public interface StoreCommandService { // week8 미션 + + Store addStore(StoreRequestDTO.AddStoreDto request); +} diff --git a/sanho/spring/src/main/java/umc/spring/service/store/StoreCommandServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/store/StoreCommandServiceImpl.java new file mode 100644 index 0000000..1e1ca0c --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/store/StoreCommandServiceImpl.java @@ -0,0 +1,36 @@ +package umc.spring.service.store; + +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.apipayload.exception.handler.RegionHandler; +import umc.spring.converter.StoreConverter; +import umc.spring.domain.Region; +import umc.spring.domain.Store; +import umc.spring.repository.region.RegionRepository; +import umc.spring.repository.store.StoreRepository; +import umc.spring.web.dto.StoreRequestDTO; + + + +@Service +@RequiredArgsConstructor +public class StoreCommandServiceImpl implements StoreCommandService { // week8 미션 + + private final StoreRepository storeRepository; + private final RegionRepository regionRepository; + + @Override + @Transactional + public Store addStore(StoreRequestDTO.AddStoreDto request) { + + Region region = regionRepository.findById(request.getRegionId()) + .orElseThrow(() -> new RegionHandler(ErrorStatus.REGION_NOT_FOUND)); + + Store newStore = StoreConverter.toStore(request, region); + newStore.setRegion(region); + + return storeRepository.save(newStore); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/service/store/StoreQueryService.java b/sanho/spring/src/main/java/umc/spring/service/store/StoreQueryService.java new file mode 100644 index 0000000..2880610 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/store/StoreQueryService.java @@ -0,0 +1,21 @@ +package umc.spring.service.store; + +import org.springframework.data.domain.Page; +import umc.spring.domain.Mission; +import umc.spring.domain.Review; +import umc.spring.domain.Store; + +import java.util.List; +import java.util.Optional; + +public interface StoreQueryService { + + Optional findStore(Long id); // null 반환 가능 + List findStoresByNameAndScore(String name, Float score); + + // week9 코드 + Page getReviewList(Long storeId, Integer page); // Page 자체에 페이징과 관련된 여러 정보가 담김 -> Paging을 위한 추상화 제공 + + // week9 미션 - 특정 가게 미션 목록 조회 + Page getMissionList(Long storeId, Integer page); +} diff --git a/sanho/spring/src/main/java/umc/spring/service/store/StoreQueryServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/store/StoreQueryServiceImpl.java new file mode 100644 index 0000000..b516a29 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/store/StoreQueryServiceImpl.java @@ -0,0 +1,61 @@ +package umc.spring.service.store; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.data.domain.Page; +import umc.spring.domain.Mission; +import umc.spring.domain.Review; +import umc.spring.domain.Store; +import umc.spring.repository.mission.MissionRepository; +import umc.spring.repository.review.ReviewRepository; +import umc.spring.repository.store.StoreRepository; +import java.util.List; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) // 조회에만 +public class StoreQueryServiceImpl implements StoreQueryService{ + + private final StoreRepository storeRepository; + private final ReviewRepository reviewRepository; + private final MissionRepository missionRepository; + + @Override + public Optional findStore(Long id) { + return storeRepository.findById(id); + } + + @Override + public List findStoresByNameAndScore(String name, Float score) { + List filteredStores = storeRepository.dynamicQueryWithBooleanBuilder(name, score); + + filteredStores.forEach(store -> System.out.println("Store: " + store)); + + return filteredStores; + } + + // week9 실습 코드 + @Override + public Page getReviewList(Long storeId, Integer page) { + Store store = storeRepository.findById(storeId).get(); // 먼저 storeId로 가게를 찾고 + +// Store store = storeRepository.findById(storeId) +// .orElseThrow(() -> new StoreHandler(ErrorStatus.STORE_NOT_FOUND)); + + Page storePage = reviewRepository.findAllByStore(store, PageRequest.of(page, 10)); // 해당 가게의 리뷰 10개 단위로 가져오기 + // Page : 데이터, 페이지 번호, 페이지 개수, 전체 데이터 개수, 페이지 크기, 페이지 여부, 정렬 정보 등 + + return storePage; + } + + // week9 미션 - 특정 가게 미션 목록 조회 + + @Override + public Page getMissionList(Long storeId, Integer page) { + Store store = storeRepository.findById(storeId).get(); + return missionRepository.findAllByStore(store, PageRequest.of(page, 10)); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/service/tempservice/TempCommandService.java b/sanho/spring/src/main/java/umc/spring/service/tempservice/TempCommandService.java new file mode 100644 index 0000000..f1ab793 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/tempservice/TempCommandService.java @@ -0,0 +1,4 @@ +package umc.spring.service.tempservice; + +public interface TempCommandService { +} diff --git a/sanho/spring/src/main/java/umc/spring/service/tempservice/TempCommandServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/tempservice/TempCommandServiceImpl.java new file mode 100644 index 0000000..987eae2 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/tempservice/TempCommandServiceImpl.java @@ -0,0 +1,9 @@ +package umc.spring.service.tempservice; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class TempCommandServiceImpl implements TempCommandService{ +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/service/tempservice/TempQueryService.java b/sanho/spring/src/main/java/umc/spring/service/tempservice/TempQueryService.java new file mode 100644 index 0000000..44ade74 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/tempservice/TempQueryService.java @@ -0,0 +1,9 @@ +package umc.spring.service.tempservice; + +import org.springframework.stereotype.Service; + +@Service +public interface TempQueryService { // 인터페이스 + + void checkFlag(Integer flag); +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/service/tempservice/TempQueryServiceImpl.java b/sanho/spring/src/main/java/umc/spring/service/tempservice/TempQueryServiceImpl.java new file mode 100644 index 0000000..f1ac189 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/service/tempservice/TempQueryServiceImpl.java @@ -0,0 +1,18 @@ +package umc.spring.service.tempservice; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.apipayload.exception.handler.TempHandler; + +@Service +@RequiredArgsConstructor +public class TempQueryServiceImpl implements TempQueryService{ // Service에서 예외를 터뜨림 + + @Override + public void checkFlag(Integer flag) { + if (flag == 1) + throw new TempHandler(ErrorStatus.TEMP_EXCEPTION); // 이건 그냥 flag가 1일 때의 예시이고, 실제로는 필요한 곳에서 해당 예외를 터뜨림 + // 여기서 Controller로 안 가고 바로 Exception handler에 의해 응답이 보내짐. @RestControllerAdvice + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/annotation/CheckPage.java b/sanho/spring/src/main/java/umc/spring/validation/annotation/CheckPage.java new file mode 100644 index 0000000..6d77f9e --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/annotation/CheckPage.java @@ -0,0 +1,17 @@ +package umc.spring.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.spring.validation.validator.PageCheckValidator; +import java.lang.annotation.*; + +@Documented // 사용자 정의 애노테이션 +@Constraint(validatedBy = PageCheckValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface CheckPage { // week9 미션 + + String message() default "해당하는 페이지가 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistCategories.java b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistCategories.java new file mode 100644 index 0000000..3e6d800 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistCategories.java @@ -0,0 +1,18 @@ +package umc.spring.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.spring.validation.validator.CategoriesExistValidator; + +import java.lang.annotation.*; + +@Documented // 사용자 정의 애노테이션 +@Constraint(validatedBy = CategoriesExistValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistCategories { // week8 미션 + + String message() default "해당하는 카테고리가 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMember.java b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMember.java new file mode 100644 index 0000000..9cb1ec6 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMember.java @@ -0,0 +1,18 @@ +package umc.spring.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.spring.validation.validator.MemberExistValidator; + +import java.lang.annotation.*; + +@Documented // 사용자 정의 애노테이션 +@Constraint(validatedBy = MemberExistValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistMember { // week9 미션 + + String message() default "해당하는 멤버가 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMemberMission.java b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMemberMission.java new file mode 100644 index 0000000..45d17ea --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMemberMission.java @@ -0,0 +1,18 @@ +package umc.spring.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.spring.validation.validator.MemberMissionExistValidator; + +import java.lang.annotation.*; + +@Documented // 사용자 정의 애노테이션 +@Constraint(validatedBy = MemberMissionExistValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistMemberMission { // week8 미션 + + String message() default "해당하는 미션이 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMission.java b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMission.java new file mode 100644 index 0000000..de7128b --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistMission.java @@ -0,0 +1,19 @@ +package umc.spring.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.spring.validation.validator.MemberExistValidator; +import umc.spring.validation.validator.MissionExistValidator; + +import java.lang.annotation.*; + +@Documented // 사용자 정의 애노테이션 +@Constraint(validatedBy = MissionExistValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistMission { // week9 미션 - 진행 중인 미션을 진행 완료로 수정하기 + + String message() default "해당하는 미션이 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistRegion.java b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistRegion.java new file mode 100644 index 0000000..4bae724 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistRegion.java @@ -0,0 +1,18 @@ +package umc.spring.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.spring.validation.validator.RegionExistValidator; + +import java.lang.annotation.*; + +@Documented // 사용자 정의 애노테이션 +@Constraint(validatedBy = RegionExistValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistRegion { // week8 미션 + + String message() default "해당하는 지역이 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistStore.java b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistStore.java new file mode 100644 index 0000000..adf3b2e --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/annotation/ExistStore.java @@ -0,0 +1,18 @@ +package umc.spring.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.spring.validation.validator.StoreExistValidator; + +import java.lang.annotation.*; + +@Documented // 사용자 정의 애노테이션 +@Constraint(validatedBy = StoreExistValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistStore { // week8 미션 + + String message() default "해당하는 가게가 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/validator/CategoriesExistValidator.java b/sanho/spring/src/main/java/umc/spring/validation/validator/CategoriesExistValidator.java new file mode 100644 index 0000000..f6e84f4 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/validator/CategoriesExistValidator.java @@ -0,0 +1,38 @@ +package umc.spring.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.repository.foodcategory.FoodCategoryRepository; +import umc.spring.validation.annotation.ExistCategories; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class CategoriesExistValidator implements ConstraintValidator> { // 여기서 바로 repository에 접근하면 안 됨 + // week8 미션 + + private final FoodCategoryRepository foodCategoryRepository; + + @Override + public void initialize(ExistCategories constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(List values, ConstraintValidatorContext context) { + boolean isValid = values.stream() + .allMatch(value -> foodCategoryRepository.existsById(value)); + + if (!isValid) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(ErrorStatus.FOOD_CATEGORY_NOT_FOUND.toString()).addConstraintViolation(); + } + + return isValid; + + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/validator/MemberExistValidator.java b/sanho/spring/src/main/java/umc/spring/validation/validator/MemberExistValidator.java new file mode 100644 index 0000000..9c8e5ac --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/validator/MemberExistValidator.java @@ -0,0 +1,40 @@ +package umc.spring.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.repository.member.MemberRepository; +import umc.spring.repository.region.RegionRepository; +import umc.spring.validation.annotation.ExistMember; +import umc.spring.validation.annotation.ExistRegion; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class MemberExistValidator implements ConstraintValidator { + // week9 미션 + + private final MemberRepository memberRepository; + + @Override + public void initialize(ExistMember constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(Long value, ConstraintValidatorContext context) { + + // 멤버 id가 null이거나, 레포지토리에 존재하지 않으면 에러 + if (value == null || !memberRepository.existsById(value)) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(ErrorStatus.MEMBER_NOT_FOUND.toString()) + .addConstraintViolation(); + return false; + } + + return true; // 검증 성공 + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/validator/MemberMissionExistValidator.java b/sanho/spring/src/main/java/umc/spring/validation/validator/MemberMissionExistValidator.java new file mode 100644 index 0000000..04c2a98 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/validator/MemberMissionExistValidator.java @@ -0,0 +1,37 @@ +package umc.spring.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.repository.membermission.MemberMissionRepository; +import umc.spring.validation.annotation.ExistMemberMission; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class MemberMissionExistValidator implements ConstraintValidator> { // 여기서 바로 repository에 접근하면 안 됨 + // week8 미션 + private final MemberMissionRepository memberMissionRepository; + + @Override + public void initialize(ExistMemberMission constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(List values, ConstraintValidatorContext context) { + boolean isValid = values.stream() + .allMatch(value -> memberMissionRepository.existsById(value)); + + if (!isValid) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(ErrorStatus.Member_Mission_NOT_FOUND.toString()).addConstraintViolation(); + } + + return isValid; + + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/validator/MissionExistValidator.java b/sanho/spring/src/main/java/umc/spring/validation/validator/MissionExistValidator.java new file mode 100644 index 0000000..57b481d --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/validator/MissionExistValidator.java @@ -0,0 +1,36 @@ +package umc.spring.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.repository.mission.MissionRepository; +import umc.spring.validation.annotation.ExistMission; + +@Component +@RequiredArgsConstructor +public class MissionExistValidator implements ConstraintValidator { + // week9 미션 - 진행 중인 미션을 진행 완료로 수정하기 + + private final MissionRepository missionRepository; + + @Override + public void initialize(ExistMission constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(Long value, ConstraintValidatorContext context) { + + // 멤버 id가 null이거나, 레포지토리에 존재하지 않으면 에러 + if (value == null || !missionRepository.existsById(value)) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(ErrorStatus.MISSION_NOT_FOUND.toString()) + .addConstraintViolation(); + return false; + } + + return true; // 검증 성공 + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/validator/PageCheckValidator.java b/sanho/spring/src/main/java/umc/spring/validation/validator/PageCheckValidator.java new file mode 100644 index 0000000..546d798 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/validator/PageCheckValidator.java @@ -0,0 +1,32 @@ +package umc.spring.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import org.springframework.stereotype.Component; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.validation.annotation.CheckPage; + +@Component +public class PageCheckValidator implements ConstraintValidator { + // week9 미션 + + @Override + public void initialize(CheckPage constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + // 여기서 페이지 번호를 -1 해주지는 못 하고 검증만 가능 + @Override + public boolean isValid(Integer value, ConstraintValidatorContext context) { + + // 요청으로 온 페이지 번호가 null이거나 1 미만이면 검증 실패 + if (value == null || value < 1) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(ErrorStatus.PAGE_NOT_FOUND.toString()) + .addConstraintViolation(); + return false; + } + + return true; // 검증 성공 + } +} diff --git a/sanho/spring/src/main/java/umc/spring/validation/validator/RegionExistValidator.java b/sanho/spring/src/main/java/umc/spring/validation/validator/RegionExistValidator.java new file mode 100644 index 0000000..565c464 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/validator/RegionExistValidator.java @@ -0,0 +1,37 @@ +package umc.spring.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.repository.region.RegionRepository; +import umc.spring.validation.annotation.ExistRegion; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class RegionExistValidator implements ConstraintValidator> { // 여기서 바로 repository에 접근하면 안 됨 + // week8 미션 + private final RegionRepository regionRepository; + + @Override + public void initialize(ExistRegion constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(List values, ConstraintValidatorContext context) { + boolean isValid = values.stream() + .allMatch(value -> regionRepository.existsById(value)); + + if (!isValid) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(ErrorStatus.REGION_NOT_FOUND.toString()).addConstraintViolation(); + } + + return isValid; + + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/validation/validator/StoreExistValidator.java b/sanho/spring/src/main/java/umc/spring/validation/validator/StoreExistValidator.java new file mode 100644 index 0000000..68c354d --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/validation/validator/StoreExistValidator.java @@ -0,0 +1,72 @@ +package umc.spring.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import umc.spring.apipayload.code.status.ErrorStatus; +import umc.spring.repository.store.StoreRepository; +import umc.spring.validation.annotation.ExistStore; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class StoreExistValidator implements ConstraintValidator { // 여기서 바로 repository에 접근하면 안 됨 + // week8 미션 + private final StoreRepository storeRepository; + + @Override + public void initialize(ExistStore constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(Long value, ConstraintValidatorContext context) { +// boolean isValid = values.stream() +// .allMatch(value -> storeRepository.existsById(value)); +// +// if (!isValid) { +// context.disableDefaultConstraintViolation(); +// context.buildConstraintViolationWithTemplate(ErrorStatus.STORE_NOT_FOUND.toString()).addConstraintViolation(); +// } +// +// return isValid; + + +// // Store ID가 null이면 검증 실패 +// if (value == null) { +// return false; +// } +// +// // StoreRepository를 사용해 존재 여부 검증 +// return storeRepository.existsById(value); + +// // Store ID가 null이면 검증 실패 +// if (value == null) { +// context.disableDefaultConstraintViolation(); +// context.buildConstraintViolationWithTemplate(ErrorStatus.STORE_NOT_FOUND.toString()).addConstraintViolation(); +// return false; +// } +// +// // StoreRepository를 사용해 존재 여부 검증 +// boolean isValid = storeRepository.existsById(value); +// if (!isValid) { +// context.disableDefaultConstraintViolation(); +// context.buildConstraintViolationWithTemplate(ErrorStatus.STORE_NOT_FOUND.toString()).addConstraintViolation(); +// } +// +// return isValid; // 검증 성공 + + + // Store ID가 null이면 검증 실패 + if (value == null || !storeRepository.existsById(value)) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(ErrorStatus.STORE_NOT_FOUND.toString()) + .addConstraintViolation(); + return false; + } + + return true; // 검증 성공 + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/web/controller/MemberRestController.java b/sanho/spring/src/main/java/umc/spring/web/controller/MemberRestController.java new file mode 100644 index 0000000..7485780 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/controller/MemberRestController.java @@ -0,0 +1,77 @@ +package umc.spring.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import umc.spring.apipayload.ApiResponse; +import umc.spring.converter.MemberConverter; +import umc.spring.domain.Member; +import umc.spring.domain.Mission; +import umc.spring.domain.Review; +import umc.spring.domain.mapping.MemberMission; +import umc.spring.service.member.MemberCommandService; +import umc.spring.service.member.MemberQueryService; +import umc.spring.validation.annotation.ExistMember; +import umc.spring.validation.annotation.CheckPage; +import umc.spring.web.dto.MemberRequestDTO; +import umc.spring.web.dto.MemberResponseDTO; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/members") +@Validated +public class MemberRestController { // week8 미션 + + private final MemberCommandService memberCommandService; + private final MemberQueryService memberQueryService; + + @PostMapping("/") + public ApiResponse join(@RequestBody @Valid MemberRequestDTO.JoinDto request) { + Member member = memberCommandService.joinMember(request); + return ApiResponse.onSuccess(MemberConverter.toJoinResultDTO(member)); // result를 리턴하는데, 이 result가 id와 생성시간 + } + + // week9 미션 - 특정 멤버 리뷰 목록 + @GetMapping("/{memberId}/reviews") + @Operation(summary = "특정 멤버의 리뷰 목록 조회 API", description = "특정 멤버의 리뷰 목록을 조회하는 API이며, 페이징을 포함합니다. query String 으로 page 번호를 주세요") + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "COMMON200",description = "OK, 성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH003", description = "access 토큰을 주세요!",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH004", description = "acess 토큰 만료",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH006", description = "acess 토큰 모양이 이상함",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + }) + @Parameters({ + @Parameter(name = "memberId", description = "멤버의 아이디, path variable 입니다!"), + @Parameter(name = "page", description = "페이지 번호, query string 입니다. 1 이상의 페이지 번호를 보내주세요!") + }) + public ApiResponse getReviewList(@ExistMember @PathVariable Long memberId, @CheckPage @RequestParam Integer page) { + Page reviewPage = memberQueryService.getReviewList(memberId, page - 1); // 여기서 1 빼주기 + return ApiResponse.onSuccess(MemberConverter.memberReviewListDTO(reviewPage)); + } + + // week9 미션 - 내가 진행 중인 미션 목록 + @GetMapping("/{memberId}/missions") + @Operation(summary = "특정 멤버의 미션 목록 조회 API", description = "특정 멤버의 미션 목록을 조회하는 API이며, 페이징을 포함합니다. query String 으로 page 번호를 주세요") + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "COMMON200",description = "OK, 성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH003", description = "access 토큰을 주세요!",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH004", description = "acess 토큰 만료",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH006", description = "acess 토큰 모양이 이상함",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + }) + @Parameters({ + @Parameter(name = "memberId", description = "멤버의 아이디, path variable 입니다!"), + @Parameter(name = "page", description = "페이지 번호, query string 입니다. 1 이상의 페이지 번호를 보내주세요!") + }) + public ApiResponse getMissionList(@ExistMember @PathVariable Long memberId, @CheckPage @RequestParam Integer page) { + Page memberMissionPage = memberQueryService.getMemberMissionList(memberId, page - 1); + return ApiResponse.onSuccess(MemberConverter.memberMissionListDTO(memberMissionPage)); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/web/controller/MissionRestController.java b/sanho/spring/src/main/java/umc/spring/web/controller/MissionRestController.java new file mode 100644 index 0000000..7c605bc --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/controller/MissionRestController.java @@ -0,0 +1,61 @@ +package umc.spring.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import umc.spring.apipayload.ApiResponse; +import umc.spring.converter.MissionConverter; +import umc.spring.converter.ReviewConverter; +import umc.spring.domain.Mission; +import umc.spring.domain.Review; +import umc.spring.domain.mapping.MemberMission; +import umc.spring.service.mission.MissionCommandService; +import umc.spring.service.mission.MissionQueryService; +import umc.spring.validation.annotation.ExistMember; +import umc.spring.validation.annotation.ExistMission; +import umc.spring.web.dto.MissionRequestDTO; +import umc.spring.web.dto.MissionResponseDTO; +import umc.spring.web.dto.ReviewRequestDTO; +import umc.spring.web.dto.ReviewResponseDTO; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/missons") +@Validated +public class MissionRestController { // week8 미션 + + private final MissionCommandService missionCommandService; + private final MissionQueryService missionQueryService; + + @PostMapping("/") + public ApiResponse add(@RequestBody @Valid MissionRequestDTO.AddMissionDTO request){ + + Mission mission = missionCommandService.addMission(request); + + return ApiResponse.onSuccess((MissionConverter.toAddMissionDTO(mission))); + } + + @PatchMapping("/{missionId}/status") + @Operation(summary = "진행 중인 미션을 진행 완료로 수정하는 API", description = "진행 중인 미션을 진행 완료로 수정하는 API입니다.") + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "COMMON200",description = "OK, 성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH003", description = "access 토큰을 주세요!",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH004", description = "acess 토큰 만료",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH006", description = "acess 토큰 모양이 이상함",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + }) + @Parameters({ + @Parameter(name = "missionId", description = "진행 완료로 수정할 미션의 아이디, path variable 입니다!"), + }) + public ApiResponse completeMission(@ExistMission @PathVariable Long missionId) { + MemberMission memberMission = missionQueryService.findMemberMission(missionId); + missionQueryService.completeMission(memberMission); + return ApiResponse.onSuccess(MissionConverter.memberMissionDTO(memberMission)); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/web/controller/ReviewRestController.java b/sanho/spring/src/main/java/umc/spring/web/controller/ReviewRestController.java new file mode 100644 index 0000000..57aa7d7 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/controller/ReviewRestController.java @@ -0,0 +1,31 @@ +package umc.spring.web.controller; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import umc.spring.apipayload.ApiResponse; +import umc.spring.converter.ReviewConverter; +import umc.spring.domain.Review; +import umc.spring.service.review.ReviewCommandService; +import umc.spring.web.dto.ReviewRequestDTO; +import umc.spring.web.dto.ReviewResponseDTO; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/reviews") +public class ReviewRestController { // week8 미션 + + private final ReviewCommandService reviewCommandService; + + @PostMapping("/") + public ApiResponse add(@RequestBody @Valid ReviewRequestDTO.AddReviewDto request){ + + Review review = reviewCommandService.addReview(request); + + return ApiResponse.onSuccess((ReviewConverter.toAddResultDTO(review))); + + } +} diff --git a/sanho/spring/src/main/java/umc/spring/web/controller/StoreRestController.java b/sanho/spring/src/main/java/umc/spring/web/controller/StoreRestController.java new file mode 100644 index 0000000..893baed --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/controller/StoreRestController.java @@ -0,0 +1,92 @@ +package umc.spring.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import umc.spring.apipayload.ApiResponse; +import umc.spring.converter.StoreConverter; +import umc.spring.domain.Mission; +import umc.spring.domain.Review; +import umc.spring.domain.Store; +import umc.spring.service.store.StoreCommandService; +import umc.spring.service.store.StoreQueryService; +import umc.spring.validation.annotation.CheckPage; +import umc.spring.validation.annotation.ExistStore; +import umc.spring.web.dto.StoreRequestDTO; +import umc.spring.web.dto.StoreResponseDTO; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/stores") +@Validated +public class StoreRestController { // week8 미션 + + private final StoreCommandService storeCommandService; + private final StoreQueryService storeQueryService; // week9 코드 + + @PostMapping("/") + public ApiResponse add(@RequestBody @Valid StoreRequestDTO.AddStoreDto request){ + Store store = storeCommandService.addStore(request); + return ApiResponse.onSuccess((StoreConverter.toAddResultDTO(store))); + + } + + // week9 실습 코드 + @GetMapping("/{storeId}/reviews") + @Operation(summary = "특정 가게의 리뷰 목록 조회 API",description = "특정 가게의 리뷰들의 목록을 조회하는 API이며, 페이징을 포함합니다. query String 으로 page 번호를 주세요") + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "COMMON200",description = "OK, 성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH003", description = "access 토큰을 주세요!",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH004", description = "acess 토큰 만료",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH006", description = "acess 토큰 모양이 이상함",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + }) + @Parameters({ + @Parameter(name = "storeId", description = "가게의 아이디, path variable 입니다!") + }) + public ApiResponse getReviewList( + @ExistStore @PathVariable(name = "storeId") Long storeId, + @CheckPage @RequestParam(name = "page") Integer page + ) { +// storeQueryService.getReviewList(storeId, page); +// return ApiResponse.onSuccess(StoreConverter.reviewPreViewListDTO(reviewList)); + + // 서비스에서 리뷰 목록 가져오기 + Page reviewPage = storeQueryService.getReviewList(storeId, page - 1); + + // DTO 변환: 리뷰 목록과 페이징 정보 + StoreResponseDTO.ReviewPreViewListDTO reviewListDTO = StoreConverter.reviewPreViewListDTO(reviewPage); + + // 성공 응답 반환 + return ApiResponse.onSuccess(reviewListDTO); + } + + // week9 미션 - 특정 가게 미션 목록 조회 + @GetMapping("/{storeId}/misisons") + @Operation(summary = "특정 가게의 미션 목록 조회 API",description = "특정 가게의 미션들의 목록을 조회하는 API이며, 페이징을 포함합니다. query String 으로 page 번호를 주세요") + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "COMMON200",description = "OK, 성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH003", description = "access 토큰을 주세요!",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH004", description = "acess 토큰 만료",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "AUTH006", description = "acess 토큰 모양이 이상함",content = @Content(schema = @Schema(implementation = ApiResponse.class))), + }) + @Parameters({ + @Parameter(name = "storeId", description = "가게의 아이디, path variable 입니다!"), + @Parameter(name = "page", description = "페이지 번호, query string 입니다. 1 이상의 페이지 번호를 보내주세요!") + }) + public ApiResponse getMissionList(@ExistStore @PathVariable Long storeId, @CheckPage @RequestParam Integer page) { + + // 서비스에서 미션 목록 가져오기 + Page missionPage = storeQueryService.getMissionList(storeId, page - 1); + + // 성공 응답 반환 + return ApiResponse.onSuccess(StoreConverter.storeMissionListDTO(missionPage)); + } +} diff --git a/sanho/spring/src/main/java/umc/spring/web/controller/TempRestController.java b/sanho/spring/src/main/java/umc/spring/web/controller/TempRestController.java new file mode 100644 index 0000000..7446f0e --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/controller/TempRestController.java @@ -0,0 +1,31 @@ +package umc.spring.web.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import umc.spring.apipayload.ApiResponse; +import umc.spring.converter.TempConverter; +import umc.spring.service.tempservice.TempQueryService; +import umc.spring.web.dto.TempResponse; + +@RestController +@RequestMapping("/temp") +@RequiredArgsConstructor +public class TempRestController { // @RestController라 json 형태로 바로 화면으로 값을 뿌림 + // week8 미션 + private final TempQueryService tempQueryService; + + @GetMapping("/test") + public ApiResponse testAPI(){ + + return ApiResponse.onSuccess(TempConverter.toTempTestDTO()); + } + + @GetMapping("/exception") + public ApiResponse exceptionAPI(@RequestParam Integer flag){ + tempQueryService.checkFlag(flag); + return ApiResponse.onSuccess(TempConverter.toTempExceptionDTO(flag)); + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/MemberRequestDTO.java b/sanho/spring/src/main/java/umc/spring/web/dto/MemberRequestDTO.java new file mode 100644 index 0000000..51d41a8 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/MemberRequestDTO.java @@ -0,0 +1,32 @@ +package umc.spring.web.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Getter; +import umc.spring.validation.annotation.ExistCategories; + +import java.util.List; + +public class MemberRequestDTO { // week8 미션 + + @Getter + public static class JoinDto{ + @NotBlank + String name; + @NotNull + Integer gender; + @NotNull + Integer birthYear; + @NotNull + Integer birthMonth; + @NotNull + Integer birthDay; + @Size(min = 5, max = 12) + String address; + @Size(min = 5, max = 12) + String specAddress; + @ExistCategories + List preferCategory; + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/MemberResponseDTO.java b/sanho/spring/src/main/java/umc/spring/web/dto/MemberResponseDTO.java new file mode 100644 index 0000000..d63c651 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/MemberResponseDTO.java @@ -0,0 +1,75 @@ +package umc.spring.web.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import umc.spring.domain.enums.MissionStatus; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +public class MemberResponseDTO { + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class JoinResultDTO{ + Long memberId; + LocalDateTime createdAt; + } + + // week9 미션 - 특정 멤버 리뷰 목록 + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MemberReviewDTO { // 닉네임, 생성 일자, 별점, 리뷰 본문 + String ownerNickname; // 닉네임 말고도 사용자의 정보 더 적을 게 있다면 여기도 DTO로 빼는 게 낫다. + // MemberInfoDTO memberInfo; - 사용자의 정보가 담긴 DTO + Float score; + String body; + LocalDate createdAt; + } + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MemberReviewListDTO { + List reviewList; + Integer listSize; + Integer totalPage; + Long totalElements; + Boolean isFirst; + Boolean isLast; + } + + // week9 미션 - 내가 진행 중인 미션 목록 + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MemberMissionDTO { + String storeName; + String missionSpec; + Integer reward; + MissionStatus status; + } + + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MemberMissionListDTO { + List missionList; + Integer listSize; + Integer totalPage; + Long totalElements; + Boolean isFirst; + Boolean isLast; + } +} \ No newline at end of file diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/MissionRequestDTO.java b/sanho/spring/src/main/java/umc/spring/web/dto/MissionRequestDTO.java new file mode 100644 index 0000000..c7ab218 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/MissionRequestDTO.java @@ -0,0 +1,32 @@ +package umc.spring.web.dto; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import umc.spring.validation.annotation.ExistMemberMission; + +import java.time.LocalDate; +import java.util.List; + +public class MissionRequestDTO { // week8 미션 + + @Getter + public static class AddMissionDTO { + + @NotNull + Integer reward; + + @NotEmpty + LocalDate deadline; + + @NotEmpty + String missionSpec; + + @NotEmpty + Long storeId; + + @ExistMemberMission + Long memberMissionId; + + } +} diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/MissionResponseDTO.java b/sanho/spring/src/main/java/umc/spring/web/dto/MissionResponseDTO.java new file mode 100644 index 0000000..65ba713 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/MissionResponseDTO.java @@ -0,0 +1,35 @@ +package umc.spring.web.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import umc.spring.domain.enums.MissionStatus; + +import java.time.LocalDateTime; +import java.util.List; + +public class MissionResponseDTO { // week8 미션 + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class AddMissionResultDTO{ + Long missionId; + LocalDateTime createdAt; + } + + // week9 미션 - 진행 중인 미션 진행 완료로 바꾸기 + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MemberMissionDTO { + String memberName; + String missionSpec; + Integer reward; + MissionStatus status; + } + +} diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/ReviewRequestDTO.java b/sanho/spring/src/main/java/umc/spring/web/dto/ReviewRequestDTO.java new file mode 100644 index 0000000..a79ee55 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/ReviewRequestDTO.java @@ -0,0 +1,31 @@ +package umc.spring.web.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import umc.spring.validation.annotation.ExistMember; +import umc.spring.validation.annotation.ExistStore; + + +public class ReviewRequestDTO { // week8 미션 + + @Getter + public static class AddReviewDto { + + @NotBlank + String title; + + @NotNull + String body; + + @NotNull + Float score; + + @ExistMember + Long memberId; + + @ExistStore + Long storeId; + } + +} diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/ReviewResponseDTO.java b/sanho/spring/src/main/java/umc/spring/web/dto/ReviewResponseDTO.java new file mode 100644 index 0000000..66282ed --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/ReviewResponseDTO.java @@ -0,0 +1,20 @@ +package umc.spring.web.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +public class ReviewResponseDTO { // week8 미션 + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class AddReviewResultDTO { + Long reviewId; + LocalDateTime createdAt; + } +} diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/StoreRequestDTO.java b/sanho/spring/src/main/java/umc/spring/web/dto/StoreRequestDTO.java new file mode 100644 index 0000000..8d65891 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/StoreRequestDTO.java @@ -0,0 +1,22 @@ +package umc.spring.web.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import umc.spring.validation.annotation.ExistRegion; + +public class StoreRequestDTO { // week8 미션 + + @Getter + public static class AddStoreDto { + + @NotBlank + String name; + + @NotNull + String address; + + @ExistRegion + Long regionId; + } +} diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/StoreResponseDTO.java b/sanho/spring/src/main/java/umc/spring/web/dto/StoreResponseDTO.java new file mode 100644 index 0000000..6dff53d --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/StoreResponseDTO.java @@ -0,0 +1,75 @@ +package umc.spring.web.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +public class StoreResponseDTO { // week8 미션 + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class AddStoreDTO { + Long storeId; + LocalDateTime createdAt; + } + + // 여기부터 week9 코드 - 리뷰 목록 조회 응답 DTO + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class ReviewPreViewListDTO { + List reviewList; + Integer listSize; + Integer totalPage; + Long totalElements; + Boolean isFirst; + Boolean isLast; + } + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class ReviewPreViewDTO { + String ownerNickname; // 닉네임 말고도 사용자의 정보 더 적을 게 있다면 여기도 DTO로 빼는 게 낫다. + // MemberInfoDTO memberInfo; - 사용자의 정보가 담긴 DTO + Float score; + String body; + LocalDate createdAt; + } + + // week9 미션 - 특정 가게 미션 목록 + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class StoreMissionDTO { + String storeName; + String missionSpec; + Integer reward; + LocalDate createdAt; + } + + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class StoreMissionListDTO { + List missionList; + Integer listSize; + Integer totalPage; + Long totalElements; + Boolean isFirst; + Boolean isLast; + } + + +} diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/TempRequest.java b/sanho/spring/src/main/java/umc/spring/web/dto/TempRequest.java new file mode 100644 index 0000000..a48750a --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/TempRequest.java @@ -0,0 +1,4 @@ +package umc.spring.web.dto; + +public class TempRequest { // @RequestBody에는 담아 오는 값이 없음 +} diff --git a/sanho/spring/src/main/java/umc/spring/web/dto/TempResponse.java b/sanho/spring/src/main/java/umc/spring/web/dto/TempResponse.java new file mode 100644 index 0000000..56add33 --- /dev/null +++ b/sanho/spring/src/main/java/umc/spring/web/dto/TempResponse.java @@ -0,0 +1,26 @@ +package umc.spring.web.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +public class TempResponse { // DTO 묶음 클래스 + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class TempTestDTO{ + String testString; + } + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class TempExceptionDTO{ + Integer flag; + } + +} \ No newline at end of file diff --git a/sanho/spring/src/main/resources/application.yml b/sanho/spring/src/main/resources/application.yml new file mode 100644 index 0000000..e692f79 --- /dev/null +++ b/sanho/spring/src/main/resources/application.yml @@ -0,0 +1,63 @@ +#spring: +# datasource: +# driver-class-name: com.mysql.cj.jdbc.Driver +# url: jdbc:mysql://localhost:3306/umc7th +# username: root +# password: +# +## jpa: +## hibernate: +## ddl-auto: create +## properties: +## hibernate: +## # show_sql: true +## format_sql: true +## +## +## logging.level: +## org.hibernate.SQL: debug +## # org.hibernate.type: trace #스프링 부트 2.x, hibernate5 +## # org.hibernate.orm.jdbc.bind: trace #스프링 부트 3.x, hibernate6 + + +# local DB 사용 +spring: + datasource: + url: jdbc:mysql://localhost:3306/study + username: root + password: ssh159357! + driver-class-name: com.mysql.cj.jdbc.Driver + sql: + init: + mode: never + jpa: + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL8Dialect + show_sql: true + format_sql: true + use_sql_comments: true + hbm2ddl: + auto: update # 처음에만 create, 나중에는 update. (create면 기존 테이블 모두 없애버리고 새로 만들게 됨) + default_batch_fetch_size: 1000 + +## RDS 사용 +#spring: +# datasource: +# url: jdbc:mysql://zipdabang-db.claedpluhwyw.ap-northeast-2.rds.amazonaws.com:3306/study +# username: 님들의 rds 루트 유저 이름 +# password: 님들의 rds 비밀번호 +# driver-class-name: com.mysql.cj.jdbc.Driver +# sql: +# init: +# mode: never +# jpa: +# properties: +# hibernate: +# dialect: org.hibernate.dialect.MySQL8Dialect +# show_sql: true +# format_sql: true +# use_sql_comments: true +# hbm2ddl: +# auto: update +# default_batch_fetch_size: 1000 \ No newline at end of file diff --git a/sanho/spring/src/test/java/umc/spring/ApplicationTests.java b/sanho/spring/src/test/java/umc/spring/ApplicationTests.java new file mode 100644 index 0000000..dc36e6c --- /dev/null +++ b/sanho/spring/src/test/java/umc/spring/ApplicationTests.java @@ -0,0 +1,13 @@ +package umc.spring; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationTests { + + @Test + void contextLoads() { + } + +}