diff --git a/restaurant/.gitignore b/restaurant/.gitignore new file mode 100644 index 00000000..c2065bc2 --- /dev/null +++ b/restaurant/.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/restaurant/build.gradle b/restaurant/build.gradle new file mode 100644 index 00000000..457341d4 --- /dev/null +++ b/restaurant/build.gradle @@ -0,0 +1,34 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.9' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' +} + +group = 'techeer' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +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 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.5.6' //쿼리 파라미터 로그 남기기 + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/restaurant/gradle/wrapper/gradle-wrapper.jar b/restaurant/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..249e5832 Binary files /dev/null and b/restaurant/gradle/wrapper/gradle-wrapper.jar differ diff --git a/restaurant/gradle/wrapper/gradle-wrapper.properties b/restaurant/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..070cb702 --- /dev/null +++ b/restaurant/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/restaurant/gradlew b/restaurant/gradlew new file mode 100755 index 00000000..a69d9cb6 --- /dev/null +++ b/restaurant/gradlew @@ -0,0 +1,240 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# 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/restaurant/gradlew.bat b/restaurant/gradlew.bat new file mode 100644 index 00000000..53a6b238 --- /dev/null +++ b/restaurant/gradlew.bat @@ -0,0 +1,91 @@ +@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=. +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/restaurant/settings.gradle b/restaurant/settings.gradle new file mode 100644 index 00000000..253a94af --- /dev/null +++ b/restaurant/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'restaurant' diff --git a/restaurant/src/main/java/techeer/restaurant/RestaurantApplication.java b/restaurant/src/main/java/techeer/restaurant/RestaurantApplication.java new file mode 100644 index 00000000..e39cbf84 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/RestaurantApplication.java @@ -0,0 +1,13 @@ +package techeer.restaurant; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RestaurantApplication { + + public static void main(String[] args) { + SpringApplication.run(RestaurantApplication.class, args); + } + +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/restaurant/controller/RestaurantController.java b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/controller/RestaurantController.java new file mode 100644 index 00000000..4dd3afaa --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/controller/RestaurantController.java @@ -0,0 +1,68 @@ +package techeer.restaurant.domain.restaurant.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import techeer.restaurant.domain.restaurant.dto.RestaurantCreateRequest; +import techeer.restaurant.domain.restaurant.dto.RestaurantInfo; +import techeer.restaurant.domain.restaurant.dto.RestaurantInfoList; +import techeer.restaurant.domain.restaurant.entity.Category; +import techeer.restaurant.domain.restaurant.entity.Restaurant; +import techeer.restaurant.domain.restaurant.service.RestaurantService; +import techeer.restaurant.global.domain.response.ResultResponse; + +import javax.validation.Valid; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static techeer.restaurant.global.domain.response.code.ResultCode.*; + +@RequestMapping("/api/v1/restaurants") +@RestController +@RequiredArgsConstructor +public class RestaurantController { + + private final RestaurantService restaurantService; + + @PostMapping + public ResponseEntity createRestaurant( + @Valid @RequestBody RestaurantCreateRequest request) { + RestaurantInfo restaurantInfo = restaurantService.createRestaurant(request); + return ResponseEntity.ok(ResultResponse.of(CREATE_RESTAURANT_SUCCESS, restaurantInfo)); + } + + @GetMapping + public ResponseEntity getAllRestaurant() { + RestaurantInfoList restaurantInfoList = restaurantService.findAllRestaurants(); + return ResponseEntity.ok(ResultResponse.of(GET_ALL_RESTAURANT_SUCCESS, restaurantInfoList)); + } + + @GetMapping(params={"category"}) + public ResponseEntity findAllRestaurantByCategory(@RequestParam("category") String category) { + RestaurantInfoList restaurantInfoList = restaurantService.findAllRestaurantsByCategory(Category.valueOf(category)); + return ResponseEntity.ok(ResultResponse.of(GET_CATEGORY_RESTAURANT_SUCCESS, restaurantInfoList)); + } + + @GetMapping("/{id}") + public ResponseEntity findRestaurantById(@PathVariable Long id) { + RestaurantInfo restaurantInfo = restaurantService.findRestaurantInfoById(id); + return ResponseEntity.ok(ResultResponse.of(GET_ONE_RESTAURANT_SUCCESS, restaurantInfo)); + } + @DeleteMapping("/{id}") + public ResponseEntity deleteRestaurant(@PathVariable Long id) { + restaurantService.deleteRestaurant(id); + return ResponseEntity.ok(ResultResponse.of(DELETE_RESTAURANT_SUCCESS, "")); + } + + @PatchMapping("/{id}") + public ResponseEntity updateRestaurantCategory( + @PathVariable Long id, + @RequestBody Map request + ) { + String category = request.get("category"); + restaurantService.updateRestaurantInfo(id, Category.valueOf(category)); + return ResponseEntity.ok(ResultResponse.of(UPDATE_RESTAURANT_SUCCESS, "")); + } +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantCreateRequest.java b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantCreateRequest.java new file mode 100644 index 00000000..ce1bd437 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantCreateRequest.java @@ -0,0 +1,19 @@ +package techeer.restaurant.domain.restaurant.dto; + + +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import techeer.restaurant.domain.restaurant.entity.Category; + +import javax.validation.constraints.NotNull; + +@Builder +@Getter +@RequiredArgsConstructor +public class RestaurantCreateRequest { + + private final String name; + private final Category category; + +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantInfo.java b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantInfo.java new file mode 100644 index 00000000..27f214a9 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantInfo.java @@ -0,0 +1,35 @@ +package techeer.restaurant.domain.restaurant.dto; + +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import techeer.restaurant.domain.restaurant.entity.Category; + +import java.time.LocalDateTime; + +@Getter +@NoArgsConstructor +public class RestaurantInfo { + + private String name; + + private Category category; + + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + private LocalDateTime createdAt; + + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + private LocalDateTime updatedAt; + + @Builder + public RestaurantInfo(String name, Category category, LocalDateTime createdAt, LocalDateTime updatedAt) { + this.name = name; + this.category = category; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + + + +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantInfoList.java b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantInfoList.java new file mode 100644 index 00000000..6fa8bae0 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/dto/RestaurantInfoList.java @@ -0,0 +1,26 @@ +package techeer.restaurant.domain.restaurant.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import techeer.restaurant.domain.restaurant.entity.Restaurant; + +import java.util.ArrayList; +import java.util.List; + +@Builder +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class RestaurantInfoList { + private List restaurantInfos = new ArrayList<>(); + + public void addAllRestaurantInfo(List restaurantInfos) { + this.restaurantInfos.addAll(restaurantInfos); + } + + public void addRestaurantInfo(RestaurantInfo restaurantInfo) { + this.restaurantInfos.add(restaurantInfo); + } +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/restaurant/entity/Category.java b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/entity/Category.java new file mode 100644 index 00000000..16c81914 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/entity/Category.java @@ -0,0 +1,5 @@ +package techeer.restaurant.domain.restaurant.entity; + +public enum Category { + 한식, 중식, 일식, 양식 +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/restaurant/entity/Restaurant.java b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/entity/Restaurant.java new file mode 100644 index 00000000..b850f1b0 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/entity/Restaurant.java @@ -0,0 +1,63 @@ +package techeer.restaurant.domain.restaurant.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import techeer.restaurant.domain.review.entity.Review; +import techeer.restaurant.global.domain.BaseEntity; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Entity +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "restaurant") +public class Restaurant extends BaseEntity { + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "restaurant_id", nullable = false) + private Long id; + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "category", nullable = false) + @Enumerated(EnumType.STRING) + private Category category; + + @OneToMany(mappedBy = "restaurant") + private List reviews = new ArrayList<>(); + +/* public void updateCategory(RestaurantUpdateRequest restaurantUpdateRequest) { + this.category = restaurantUpdateRequest.getCategory(); + }*/ + + @Builder + public Restaurant(String name, Category category) { + this.name = name; + this.category = category; + this.isActive = true; + } + +// @Override +// public boolean equals(Object o) { +// if (this == o) return true; +// if (o == null || getClass() != o.getClass()) return false; +// Restaurant restaurant = (Restaurant) o; +// return Objects.equals(id, restaurant.id) +// && Objects.equals(name, restaurant.name) +// && Objects.equals(category, restaurant.category); +// } + + public void deleteRestaurant() { + this.activeOff(); + } + public void updateCategory(Category category){ this.category = category; } + + +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/restaurant/repository/RestaurantRepository.java b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/repository/RestaurantRepository.java new file mode 100644 index 00000000..ce20f818 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/repository/RestaurantRepository.java @@ -0,0 +1,23 @@ +package techeer.restaurant.domain.restaurant.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import techeer.restaurant.domain.restaurant.entity.Category; +import techeer.restaurant.domain.restaurant.entity.Restaurant; + +import java.util.List; + +@Repository +public interface RestaurantRepository extends JpaRepository { + + @Query("select R from Restaurant R where R.id= :id and R.isActive is true") + Restaurant findRestaurantById(@Param("id") Long id); + + @Query("select R from Restaurant R where R.isActive is true") + List findAllRestaurant(); + + @Query("select R from Restaurant R where R.category= :category and R.isActive is true") + List findAllRestaurantByCategory(@Param("category") Category category); +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/restaurant/service/RestaurantService.java b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/service/RestaurantService.java new file mode 100644 index 00000000..728ec57f --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/restaurant/service/RestaurantService.java @@ -0,0 +1,98 @@ +package techeer.restaurant.domain.restaurant.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import techeer.restaurant.domain.restaurant.dto.RestaurantCreateRequest; +import techeer.restaurant.domain.restaurant.dto.RestaurantInfo; +import techeer.restaurant.domain.restaurant.dto.RestaurantInfoList; +import techeer.restaurant.domain.restaurant.entity.Category; +import techeer.restaurant.domain.restaurant.entity.Restaurant; +import techeer.restaurant.domain.restaurant.repository.RestaurantRepository; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class RestaurantService { + + + private final RestaurantRepository restaurantRepository; + public RestaurantInfoList findAllRestaurants() { + List restaurants = restaurantRepository.findAllRestaurant(); + return getRestaurantInfoList(restaurants); + } + + + public RestaurantInfoList findAllRestaurantsByCategory(Category category) { + List restaurants = restaurantRepository.findAllRestaurantByCategory(category); + return getRestaurantInfoList(restaurants); + } + + private RestaurantInfoList getRestaurantInfoList(List restaurants) { + List restaurantInfos = new ArrayList<>(); + for(int i = 0; i < restaurants.size(); i++) { + restaurantInfos.add(RestaurantInfo.builder() + .name(restaurants.get(i).getName()) + .category(restaurants.get(i).getCategory()) + .createdAt(restaurants.get(i).getCreatedAt()) + .updatedAt(restaurants.get(i).getUpdatedAt()) + .build()); + } + + return new RestaurantInfoList(restaurantInfos); + } + + public RestaurantInfo createRestaurant(RestaurantCreateRequest restaurantCreateRequest) { + Restaurant newRestaurant = convertRestaurantFromRequest(restaurantCreateRequest); + Restaurant savedRestaurant = restaurantRepository.save(newRestaurant); + return mapRestaurantEntityToRestaurantInfoResponse(savedRestaurant); + } + + private RestaurantInfo mapRestaurantEntityToRestaurantInfoResponse(Restaurant savedRestaurant) { + return RestaurantInfo.builder() + .name(savedRestaurant.getName()) + .category(savedRestaurant.getCategory()) + .createdAt(savedRestaurant.getCreatedAt()) + .updatedAt(savedRestaurant.getUpdatedAt()) + .build(); + } + + + private Restaurant convertRestaurantFromRequest(RestaurantCreateRequest restaurantCreateRequest) { + return Restaurant.builder() + .name(restaurantCreateRequest.getName()) + .category(restaurantCreateRequest.getCategory()) + .build(); + } + + + public RestaurantInfo findRestaurantInfoById(Long id) { + Restaurant foundRestaurant = findRestaurantById(id); + restaurantRepository.save(foundRestaurant); + return mapRestaurantEntityToRestaurantInfoResponse(foundRestaurant); + } + + + public void deleteRestaurant(Long id) { + Restaurant foundRestaurant = findRestaurantById(id); + foundRestaurant.deleteRestaurant(); + restaurantRepository.save(foundRestaurant); + } + + + private Restaurant findRestaurantById(Long id) { + return restaurantRepository.findRestaurantById(id); + } + + + public void updateRestaurantInfo(Long id, Category category) { + Restaurant restaurant = restaurantRepository.findRestaurantById(id); + restaurant.updateCategory(category); + restaurantRepository.save(restaurant); + } +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/review/controller/ReviewController.java b/restaurant/src/main/java/techeer/restaurant/domain/review/controller/ReviewController.java new file mode 100644 index 00000000..8b5cffe6 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/review/controller/ReviewController.java @@ -0,0 +1,63 @@ +package techeer.restaurant.domain.review.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import techeer.restaurant.domain.review.dto.ReviewInfo; +import techeer.restaurant.domain.review.dto.ReviewRequest; +import techeer.restaurant.domain.review.dto.UpdateReviewRequest; +import techeer.restaurant.domain.review.service.ReviewService; +import techeer.restaurant.global.domain.response.ResultResponse; + +import javax.validation.Valid; + +import java.util.List; + +import static techeer.restaurant.global.domain.response.code.ResultCode.*; + +@RequestMapping("/api/v1/reviews") +@RestController +@RequiredArgsConstructor +public class ReviewController { + + private final ReviewService reviewService; + @PostMapping + public ResponseEntity createReview( + @Valid @RequestBody ReviewRequest request + ) { + ReviewInfo reviewInfo = reviewService.createReview(request); + return ResponseEntity.ok(ResultResponse.of(CREATE_REVIEW_SUCCESS, reviewInfo)); + } + + @GetMapping("/{id}") + public ResponseEntity findReviewById(@PathVariable Long id) { + ReviewInfo reviewInfo = reviewService.findReviewInfoById(id); + return ResponseEntity.ok(ResultResponse.of(GET_ONE_REVIEW_SUCCESS, reviewInfo)); + } + + @GetMapping + public ResponseEntity getReviews(@RequestParam(required = false, defaultValue = "0") Integer page, + @RequestParam(required = false, defaultValue = "3") Integer size, + @RequestParam(required = false, defaultValue = "") String title, + @RequestParam(required = false, defaultValue = "") String content, + @RequestParam(required = false, defaultValue = "false") String descending) { + List reviewInfos = reviewService.findAllWithPagination(page, size, title, content, Boolean.parseBoolean(descending)); + return ResponseEntity.ok(ResultResponse.of(GET_ALL_REVIEW_SUCCESS, reviewInfos)); + } + + @PatchMapping("/{id}") + public ResponseEntity updateReview( + @PathVariable Long id, + @RequestBody UpdateReviewRequest request + ) { + reviewService.updateReviewInfo(id, request); + return ResponseEntity.ok(ResultResponse.of(UPDATE_RESTAURANT_SUCCESS, "")); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteRestaurant(@PathVariable Long id) { + reviewService.deleteReview(id); + return ResponseEntity.ok(ResultResponse.of(DELETE_REVIEW_SUCCESS, "")); + } + +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/review/dto/ReviewInfo.java b/restaurant/src/main/java/techeer/restaurant/domain/review/dto/ReviewInfo.java new file mode 100644 index 00000000..7632741d --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/review/dto/ReviewInfo.java @@ -0,0 +1,43 @@ +package techeer.restaurant.domain.review.dto; + +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import techeer.restaurant.domain.restaurant.entity.Restaurant; +import techeer.restaurant.domain.review.entity.Review; + +import java.time.LocalDateTime; + +@Getter +@NoArgsConstructor +public class ReviewInfo { + + private Long reviewId; + private String restaurantName; + private String title; + private String content; + private LocalDateTime createdAt; + + + @Builder + public ReviewInfo( + Long reviewId, String restaurantName, String title, String content, LocalDateTime createdAt) { + this.reviewId = reviewId; + this.restaurantName = restaurantName; + this.title = title; + this.content = content; + this.createdAt = createdAt; + } + + public static ReviewInfo of( + Review entity + ) { + return ReviewInfo.builder() + .reviewId(entity.getId()) + .restaurantName(entity.getRestaurant().getName()) + .title(entity.getTitle()) + .content(entity.getContent()) + .createdAt(entity.getCreatedAt()) + .build(); + } +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/review/dto/ReviewRequest.java b/restaurant/src/main/java/techeer/restaurant/domain/review/dto/ReviewRequest.java new file mode 100644 index 00000000..b964ce89 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/review/dto/ReviewRequest.java @@ -0,0 +1,15 @@ +package techeer.restaurant.domain.review.dto; + +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Builder +@Getter +@RequiredArgsConstructor +public class ReviewRequest { + + private final Long restaurantId; + private final String title; + private final String content; +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/review/dto/UpdateReviewRequest.java b/restaurant/src/main/java/techeer/restaurant/domain/review/dto/UpdateReviewRequest.java new file mode 100644 index 00000000..442cb979 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/review/dto/UpdateReviewRequest.java @@ -0,0 +1,13 @@ +package techeer.restaurant.domain.review.dto; + +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Builder +@Getter +@RequiredArgsConstructor +public class UpdateReviewRequest { + private final String title; + private final String content; +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/review/entity/Review.java b/restaurant/src/main/java/techeer/restaurant/domain/review/entity/Review.java new file mode 100644 index 00000000..13a6fb9f --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/review/entity/Review.java @@ -0,0 +1,53 @@ +package techeer.restaurant.domain.review.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import techeer.restaurant.domain.restaurant.entity.Restaurant; +import techeer.restaurant.global.domain.BaseEntity; + +import javax.persistence.*; + +import static javax.persistence.FetchType.LAZY; + +@Entity +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "review") +public class Review extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "review_id", nullable = false) + private Long id; + + @ManyToOne(fetch = LAZY) + @JoinColumn(name = "restaurant_id", nullable = false) + private Restaurant restaurant; + + @Column(name = "title", nullable = false) + private String title; + + @Column(name = "content", nullable = false) + private String content; + + @Builder + public Review(String title, String content, Restaurant restaurant) { + this.title = title; + this.content = content; + this.restaurant = restaurant; + this.isActive = true; + } + + public void updateTitle(String title) { + this.title = title; + } + + public void updateContent(String content) { + this.content = content; + } + +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/review/repository/ReviewRepository.java b/restaurant/src/main/java/techeer/restaurant/domain/review/repository/ReviewRepository.java new file mode 100644 index 00000000..014d24a1 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/review/repository/ReviewRepository.java @@ -0,0 +1,26 @@ +package techeer.restaurant.domain.review.repository; + +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import techeer.restaurant.domain.review.entity.Review; + +import java.util.List; + +@Repository +public interface ReviewRepository extends JpaRepository { + @Query(value = "select R from Review R where R.id = :id and R.isActive = true") + Review findReviewById(@Param("id") Long id); + + @Query(value = "SELECT r\n " + + "FROM Review r\n " + + "WHERE (r.title = '' OR r.title Like CONCAT('%', :title, '%'))\n " + + "AND (r.content = '' OR r.content Like CONCAT('%', :content, '%'))\n") + List findAllWithFieldQuery( + String title, + String content, + Pageable pageable + ); +} diff --git a/restaurant/src/main/java/techeer/restaurant/domain/review/service/ReviewService.java b/restaurant/src/main/java/techeer/restaurant/domain/review/service/ReviewService.java new file mode 100644 index 00000000..4154ffde --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/domain/review/service/ReviewService.java @@ -0,0 +1,100 @@ +package techeer.restaurant.domain.review.service; + + +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import techeer.restaurant.domain.restaurant.entity.Restaurant; +import techeer.restaurant.domain.restaurant.repository.RestaurantRepository; +import techeer.restaurant.domain.review.dto.ReviewInfo; +import techeer.restaurant.domain.review.dto.ReviewRequest; +import techeer.restaurant.domain.review.dto.UpdateReviewRequest; +import techeer.restaurant.domain.review.entity.Review; +import techeer.restaurant.domain.review.repository.ReviewRepository; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class ReviewService { + + private final RestaurantRepository restaurantRepository; + private final ReviewRepository reviewRepository; + + public ReviewInfo createReview(ReviewRequest request) { + Review newReview = convertReviewFromRequest(request); + Review savedReview = reviewRepository.save(newReview); + return mapReviewEntityToReviewInfoResponse(savedReview); + } + + private Review convertReviewFromRequest(ReviewRequest request) { + Restaurant foundRestaurant = getRestaurantById(request.getRestaurantId()); + + return Review.builder() + .title(request.getTitle()) + .content(request.getContent()) + .restaurant(foundRestaurant) + .build(); + } + + private Restaurant getRestaurantById(Long restaurantId) { + return restaurantRepository.findRestaurantById(restaurantId); + } + + private ReviewInfo mapReviewEntityToReviewInfoResponse(Review review) { + return ReviewInfo.builder() + .reviewId(review.getId()) + .title(review.getTitle()) + .content(review.getContent()) + .restaurantName(review.getRestaurant().getName()) + .createdAt(review.getCreatedAt()) + .build(); + } + + public void deleteReview(Long id) { + reviewRepository.deleteById(id); + } + + public void updateReviewInfo(Long id, UpdateReviewRequest request) { + Review review = reviewRepository.findReviewById(id); + review.updateTitle(request.getTitle()); + review.updateContent(request.getContent()); + reviewRepository.save(review); + } + + public ReviewInfo findReviewInfoById(Long id) { + Review review = findReviewById(id); + reviewRepository.save(review); + return mapReviewEntityToReviewInfoResponse(review); + } + + public Review findReviewById(Long id) { + return reviewRepository.findReviewById(id); + } + + public List findAllWithPagination( + Integer page, + Integer size, + String title, + String content, + boolean descending + ) { + PageRequest pageRequest = PageRequest.of( + page, + size, + descending ? Sort.by("createdAt").descending() : Sort.by("createdAt").ascending() + ); + + return reviewRepository.findAllWithFieldQuery( + title, + content, + pageRequest + ) + .stream() + .map(ReviewInfo::of) + .collect(Collectors.toList()); + } +} diff --git a/restaurant/src/main/java/techeer/restaurant/global/config/JpaAuditingConfig.java b/restaurant/src/main/java/techeer/restaurant/global/config/JpaAuditingConfig.java new file mode 100644 index 00000000..6c944671 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/global/config/JpaAuditingConfig.java @@ -0,0 +1,12 @@ +package techeer.restaurant.global.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +//원래 Application에 설정할 애너테이션들을 여기에 넣음 (@Configuration에 의해) + +@EnableJpaAuditing //createdAt, updatedAt 설정 +@Configuration //애플리케이션 실행될때 실행 +public class JpaAuditingConfig { + +} diff --git a/restaurant/src/main/java/techeer/restaurant/global/domain/BaseEntity.java b/restaurant/src/main/java/techeer/restaurant/global/domain/BaseEntity.java new file mode 100644 index 00000000..59cb9938 --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/global/domain/BaseEntity.java @@ -0,0 +1,27 @@ +package techeer.restaurant.global.domain; + +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.Column; +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; +import java.time.LocalDateTime; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public class BaseEntity { + @CreatedDate protected LocalDateTime createdAt; + @LastModifiedDate private LocalDateTime updatedAt; + + @Getter + @Column(name = "is_active", nullable = false) + protected boolean isActive; + + public void activeOff() { + this.isActive = false; + } +} diff --git a/restaurant/src/main/java/techeer/restaurant/global/domain/response/ResultResponse.java b/restaurant/src/main/java/techeer/restaurant/global/domain/response/ResultResponse.java new file mode 100644 index 00000000..72120bcf --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/global/domain/response/ResultResponse.java @@ -0,0 +1,25 @@ +package techeer.restaurant.global.domain.response; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import techeer.restaurant.global.domain.response.code.ResultCode; + +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class ResultResponse { + private String code; + private String message; + private Object data; + + public static ResultResponse of(ResultCode resultCode, Object data) { + return new ResultResponse(resultCode, data); + } + + public ResultResponse(ResultCode resultCode, Object data) { + this.code = resultCode.getCode(); + this.message = resultCode.getMessage(); + this.data = data; + } +} diff --git a/restaurant/src/main/java/techeer/restaurant/global/domain/response/code/ResultCode.java b/restaurant/src/main/java/techeer/restaurant/global/domain/response/code/ResultCode.java new file mode 100644 index 00000000..a5be5e3e --- /dev/null +++ b/restaurant/src/main/java/techeer/restaurant/global/domain/response/code/ResultCode.java @@ -0,0 +1,28 @@ +package techeer.restaurant.global.domain.response.code; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum ResultCode { + + // restaurant + CREATE_RESTAURANT_SUCCESS("R001", "레스토랑 생성 성공"), + UPDATE_RESTAURANT_SUCCESS("R002", "레스토랑 수정 성공"), + GET_ALL_RESTAURANT_SUCCESS("R003-1", "레스토랑 전체 조회 성공"), + GET_CATEGORY_RESTAURANT_SUCCESS("R003-2", "레스토랑 카테고리 별 조회 성공"), + GET_ONE_RESTAURANT_SUCCESS("R004", "레스토랑 단일 조회 성공"), + DELETE_RESTAURANT_SUCCESS("R005", "레스토랑 삭제 성공"), + + //review + GET_ALL_REVIEW_SUCCESS("RV001", "리뷰 전체 조회 성공"), + GET_ONE_REVIEW_SUCCESS("RV002", "리뷰 단일 조회 성공"), + UPDATE_REVIEW_SUCCESS("RV003", "리뷰 수정 성공"), + CREATE_REVIEW_SUCCESS("RV004", "리뷰 생성 성공"), + DELETE_REVIEW_SUCCESS("RV005", "리뷰 삭제 성공"), + ; + + private final String code; + private final String message; +} diff --git a/restaurant/src/main/resources/application.yml b/restaurant/src/main/resources/application.yml new file mode 100644 index 00000000..e1f06981 --- /dev/null +++ b/restaurant/src/main/resources/application.yml @@ -0,0 +1,18 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/restaurant?serverTimezone=Asia/Seoul + username: root + password: root0707 + + jpa: + hibernate: + ddl-auto: create + properties: + hibernate: + show_sql: true + format_sql: true + +logging.level: + org.hibernate.SQL: debug + org.hibernate.type: trace \ No newline at end of file diff --git a/restaurant/src/main/resources/index.html b/restaurant/src/main/resources/index.html new file mode 100644 index 00000000..e69de29b diff --git a/restaurant/src/test/java/techeer/restaurant/RestaurantApplicationTests.java b/restaurant/src/test/java/techeer/restaurant/RestaurantApplicationTests.java new file mode 100644 index 00000000..88c61b5b --- /dev/null +++ b/restaurant/src/test/java/techeer/restaurant/RestaurantApplicationTests.java @@ -0,0 +1,13 @@ +package techeer.restaurant; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RestaurantApplicationTests { + + @Test + void contextLoads() { + } + +}