diff --git a/.env b/.env new file mode 100644 index 00000000..1503be62 --- /dev/null +++ b/.env @@ -0,0 +1,5 @@ +MYSQL_ROOT_HOST=% +MYSQL_ROOT_PASSWORD=1234 +MYSQL_DATABASE=board_dsg + +SPRING_DATASOURCE_USERNAME=root \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..c2065bc2 --- /dev/null +++ b/.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/Docker-compose.yml b/Docker-compose.yml new file mode 100644 index 00000000..ceefc50b --- /dev/null +++ b/Docker-compose.yml @@ -0,0 +1,42 @@ +version: '3' + +services: + database: + container_name: mysql_db + image: mysql + restart: unless-stopped + env_file: + - .env + ports: + - "3306:3306" + volumes: + - ./mysql/conf.d:/etc/mysql/conf.d # MySQL 설정 파일 위치 + command: + - "mysqld" + - "--character-set-server=utf8mb4" + - "--collation-server=utf8mb4_unicode_ci" + networks: + - techeer_network + + application: + container_name: springboot_backend + restart: on-failure + build: + context: ./ + dockerfile: Dockerfile + ports: + - "8080:8080" + env_file: + - .env + environment: + SPRING_DATASOURCE_URL: jdbc:mysql://mysql_db:3306/${MYSQL_DATABASE}?useSSL=false&allowPublicKeyRetrieval=true + SPRING_DATASOURCE_USERNAME: ${SPRING_DATASOURCE_USERNAME} + SPRING_DATASOURCE_PASSWORD: ${MYSQL_ROOT_PASSWORD} + depends_on: + - database + networks: + - techeer_network + +networks: + techeer_network: + driver: bridge \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..15caf4a2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,6 @@ +FROM amazoncorretto:17 +COPY build/libs/*.jar app.jar +ENTRYPOINT [ \ + "java", \ + "-jar", \ + "app.jar"] \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..8bb877c6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,53 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.9' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' + id 'org.asciidoctor.jvm.convert' version '3.3.2' +} + +group = 'com.techeer' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '17' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +ext { + set('snippetsDir', file("build/generated-snippets")) +} + +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' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + runtimeOnly 'com.h2database:h2' +// compileOnly 'mysql:mysql-connector-java' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' +} + +tasks.named('test') { + outputs.dir snippetsDir + useJUnitPlatform() +} + +tasks.named('asciidoctor') { + inputs.dir snippetsDir + dependsOn test +} + +jar { + enabled = false +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..249e5832 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..070cb702 --- /dev/null +++ b/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/gradlew b/gradlew new file mode 100755 index 00000000..a69d9cb6 --- /dev/null +++ b/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/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..f127cfd4 --- /dev/null +++ b/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/settings.gradle b/settings.gradle new file mode 100644 index 00000000..85449a35 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'Good-Night-Hackathon-SpringBoot' \ No newline at end of file diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/GoodNightHackathonSpringBootApplication.java b/src/main/java/com/techeer/goodnighthackathonspringboot/GoodNightHackathonSpringBootApplication.java new file mode 100644 index 00000000..1ce71def --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/GoodNightHackathonSpringBootApplication.java @@ -0,0 +1,13 @@ +package com.techeer.goodnighthackathonspringboot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class GoodNightHackathonSpringBootApplication { + + public static void main(String[] args) { + SpringApplication.run(GoodNightHackathonSpringBootApplication.class, args); + } + +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/controller/HelloController.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/controller/HelloController.java new file mode 100644 index 00000000..44575131 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/controller/HelloController.java @@ -0,0 +1,28 @@ +package com.techeer.goodnighthackathonspringboot.domain.hello.controller; + +import com.techeer.goodnighthackathonspringboot.domain.hello.dto.HelloDto; +import com.techeer.goodnighthackathonspringboot.domain.hello.service.HelloService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api/v1/hello") +@RequiredArgsConstructor +public class HelloController { + private final HelloService helloService; + + @PostMapping + public HelloDto create(@RequestBody HelloDto dto){ + return helloService.create(dto); + } + + @DeleteMapping + public void delete(@RequestBody HelloDto dto){ + helloService.delete(dto); + } + + @GetMapping + public String test(){ + return "Test"; + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/dao/HelloRepository.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/dao/HelloRepository.java new file mode 100644 index 00000000..e91f2b43 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/dao/HelloRepository.java @@ -0,0 +1,11 @@ +package com.techeer.goodnighthackathonspringboot.domain.hello.dao; + +import com.techeer.goodnighthackathonspringboot.domain.hello.domain.entity.Hello; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface HelloRepository extends JpaRepository { + Optional findById(Long id); + void deleteById(Long id); +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/domain/entity/Hello.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/domain/entity/Hello.java new file mode 100644 index 00000000..ce132637 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/domain/entity/Hello.java @@ -0,0 +1,20 @@ +package com.techeer.goodnighthackathonspringboot.domain.hello.domain.entity; + +import lombok.*; + +import javax.persistence.*; + +@Getter +@Entity +@AllArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Builder +@Table(name = "hello") +public class Hello { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "contents") + private String contents; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/dto/HelloDto.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/dto/HelloDto.java new file mode 100644 index 00000000..97e250e3 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/dto/HelloDto.java @@ -0,0 +1,13 @@ +package com.techeer.goodnighthackathonspringboot.domain.hello.dto; + +import lombok.Builder; +import lombok.Getter; + +@Builder +@Getter +public class HelloDto { + + private Long id; + + private String contents; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/service/HelloService.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/service/HelloService.java new file mode 100644 index 00000000..f76b5957 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/hello/service/HelloService.java @@ -0,0 +1,27 @@ +package com.techeer.goodnighthackathonspringboot.domain.hello.service; + +import com.techeer.goodnighthackathonspringboot.domain.hello.domain.entity.Hello; +import com.techeer.goodnighthackathonspringboot.domain.hello.dao.HelloRepository; +import com.techeer.goodnighthackathonspringboot.domain.hello.dto.HelloDto; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class HelloService { + + private final HelloRepository helloRepository; + + public HelloDto create(HelloDto dto){ + String contents = dto.getContents(); + Hello entity = Hello.builder() + .contents(contents) + .build(); + Hello savedEntity = helloRepository.save(entity); + return HelloDto.builder().id(savedEntity.getId()).contents(savedEntity.getContents()).build(); + } + + public void delete(HelloDto dto){ + helloRepository.deleteById(dto.getId()); + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/controller/RestaurantController.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/controller/RestaurantController.java new file mode 100644 index 00000000..a675d659 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/controller/RestaurantController.java @@ -0,0 +1,64 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.controller; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Category; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.RestaurantPageInfo; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.mapper.RestaurantMapper; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.request.RestaurantCreateRequest; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.RestaurantInfo; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.request.RestaurantUpdateRequest; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.service.RestaurantService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +@RequestMapping("/api/v1/restaurant") +@RestController +@RequiredArgsConstructor +public class RestaurantController { + private final RestaurantService restaurantService; + private final RestaurantMapper mapper; + + @PostMapping + public ResponseEntity register( + @Valid @RequestBody RestaurantCreateRequest request) { + return ResponseEntity.ok(restaurantService.create(request)); + } + + @PutMapping + public ResponseEntity update( + @Valid @RequestBody RestaurantUpdateRequest request + ){ + return ResponseEntity.ok(restaurantService.update(request)); + } + + @GetMapping("/page") + public ResponseEntity getRestaurantByPagination( + @RequestParam(defaultValue = "0") int offset, @RequestParam(defaultValue = "10") int size){ + RestaurantPageInfo restaurantPageInfo = restaurantService.getRestaurantByPagination(offset, size); + return ResponseEntity.ok(restaurantPageInfo); + } + + @GetMapping("/page/{category}") + public ResponseEntity getRestaurantByCategoryAndPagination( + @RequestParam(defaultValue = "0") int offset, + @RequestParam(defaultValue = "10") int size, + @PathVariable String category){ + RestaurantPageInfo restaurantPageInfo = restaurantService.getRestaurantByCategoryAndPagination(offset, size, Category.valueOf(category)); + return ResponseEntity.ok(restaurantPageInfo); + } + + @GetMapping("/{id}") + public ResponseEntity getOneRestaurant(@PathVariable Long id){ + RestaurantInfo restaurantInfo = restaurantService.getOneRestaurant(id); + return ResponseEntity.ok(restaurantInfo); + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + restaurantService.delete(id); + return ResponseEntity.noContent().build(); + } + +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dao/RestaurantRepository.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dao/RestaurantRepository.java new file mode 100644 index 00000000..f77220ad --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dao/RestaurantRepository.java @@ -0,0 +1,17 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.dao; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Category; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Restaurant; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +public interface RestaurantRepository extends JpaRepository { + + @Query("select r from Restaurant r where r.isActivated is true") + Page findRestaurantWithPagination(Pageable pageable); + + @Query("select r from Restaurant r where r.isActivated is true and r.category = ?1") + Page findRestaurantWithCategoryAndPagination(Category category, Pageable pageable); +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/domain/Category.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/domain/Category.java new file mode 100644 index 00000000..3bd475b0 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/domain/Category.java @@ -0,0 +1,17 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.domain; + +public enum Category { + KOREA("한식"), + CHINA("중식"), + JAPAN("일식"); + + private final String description; + + Category(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/domain/Restaurant.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/domain/Restaurant.java new file mode 100644 index 00000000..a10e0e45 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/domain/Restaurant.java @@ -0,0 +1,42 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.domain; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.RestaurantInfo; +import com.techeer.goodnighthackathonspringboot.global.domain.BaseEntity; +import lombok.*; + +import javax.persistence.*; + +@Entity +@Getter +@AllArgsConstructor +@NoArgsConstructor(access= AccessLevel.PROTECTED) +@Table(name = "restaurant") +public class Restaurant extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "category") + @Enumerated(EnumType.STRING) + private Category category; + + @Builder + public Restaurant(String name, Category category){ + this.name = name; + this.category = category; + this.isActivated = true; + } + + public void delete(){ + this.activeOff(); + } + + public void update(RestaurantInfo restaurantInfo){ + this.category = restaurantInfo.getCategory(); + } + +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/RestaurantInfo.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/RestaurantInfo.java new file mode 100644 index 00000000..6506f509 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/RestaurantInfo.java @@ -0,0 +1,20 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.dto; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Category; +import lombok.*; +import org.springframework.format.annotation.DateTimeFormat; + +import java.time.LocalDateTime; + +@Getter +@Builder +@AllArgsConstructor +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class RestaurantInfo { + + private String name; + private Category category; + + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + private LocalDateTime createdOn; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/RestaurantPageInfo.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/RestaurantPageInfo.java new file mode 100644 index 00000000..b905c981 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/RestaurantPageInfo.java @@ -0,0 +1,16 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Builder +@AllArgsConstructor +@Getter +@NoArgsConstructor +public class RestaurantPageInfo { + private List restaurantInfos; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/mapper/RestaurantMapper.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/mapper/RestaurantMapper.java new file mode 100644 index 00000000..2e2e1e74 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/mapper/RestaurantMapper.java @@ -0,0 +1,60 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.mapper; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Category; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Restaurant; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.RestaurantPageInfo; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.request.RestaurantCreateRequest; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.RestaurantInfo; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.request.RestaurantUpdateRequest; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.response.RestaurantResponseDto; +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class RestaurantMapper { + + public RestaurantResponseDto toResponseDto(Restaurant entity) { + return RestaurantResponseDto.builder() + .name(entity.getName()) + .category(entity.getCategory().toString()) + .build(); + } + + public RestaurantInfo mapCreateRequestToInfo(RestaurantCreateRequest request) { + return RestaurantInfo.builder() + .name(request.getName()) + .category(Category.valueOf(request.getCategory())) + .build(); + } + + public RestaurantInfo mapUpdateRequestToInfo(RestaurantUpdateRequest request) { + return RestaurantInfo.builder() + .category(Category.valueOf(request.getCategory())) + .build(); + } + + public Restaurant toEntity(RestaurantCreateRequest request) { + return Restaurant.builder() + .name(request.getName()) + .category(Category.valueOf(request.getCategory())) + .build(); + } + + public RestaurantInfo mapEntityToInfo(Restaurant entity) { + return RestaurantInfo.builder() + .name(entity.getName()) + .category(entity.getCategory()) + .createdOn(entity.getCreateOn()) + .build(); + } + + public RestaurantPageInfo mapEntityToRestaurantPageInfo(Page restaurantList) { + List restaurantInfoList = + restaurantList.stream().map(this::mapEntityToInfo).collect(Collectors.toList()); + return RestaurantPageInfo.builder().restaurantInfos(restaurantInfoList).build(); + } + +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/request/RestaurantCreateRequest.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/request/RestaurantCreateRequest.java new file mode 100644 index 00000000..cd23485a --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/request/RestaurantCreateRequest.java @@ -0,0 +1,18 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.request; + +import lombok.*; + +import javax.validation.constraints.NotBlank; + +@Builder +@AllArgsConstructor +@Getter +@RequiredArgsConstructor +public class RestaurantCreateRequest { + @NotBlank(message = "레스토랑 이름은 필수입니다.") + private String name; + + @NotBlank(message = "레스토랑 카테고리는 필수입니다.") + private String category; + +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/request/RestaurantUpdateRequest.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/request/RestaurantUpdateRequest.java new file mode 100644 index 00000000..aab4455c --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/request/RestaurantUpdateRequest.java @@ -0,0 +1,21 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.request; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Builder +@AllArgsConstructor +@Getter +@RequiredArgsConstructor +public class RestaurantUpdateRequest { + @NotNull(message = "레스토랑 id는 필수입니다.") + private Long id; + + @NotBlank(message = "레스토랑 카테고리는 필수입니다.") + private String category; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/response/RestaurantResponseDto.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/response/RestaurantResponseDto.java new file mode 100644 index 00000000..d053a695 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/dto/response/RestaurantResponseDto.java @@ -0,0 +1,12 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.response; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Category; +import lombok.Builder; +import lombok.Getter; + +@Builder +@Getter +public class RestaurantResponseDto { + private String name; + private String category; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/exception/NotFoundRestaurantException.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/exception/NotFoundRestaurantException.java new file mode 100644 index 00000000..4416fb28 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/exception/NotFoundRestaurantException.java @@ -0,0 +1,10 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.exception; + +import com.techeer.goodnighthackathonspringboot.global.error.ErrorCode; +import com.techeer.goodnighthackathonspringboot.global.exception.BusinessException; + +public class NotFoundRestaurantException extends BusinessException { + public NotFoundRestaurantException() { + super(ErrorCode.NOT_FOUND_RESTAURANT_ENTITY); + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/service/RestaurantService.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/service/RestaurantService.java new file mode 100644 index 00000000..58be279b --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/restaurant/service/RestaurantService.java @@ -0,0 +1,70 @@ +package com.techeer.goodnighthackathonspringboot.domain.restaurant.service; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dao.RestaurantRepository; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Category; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Restaurant; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.RestaurantPageInfo; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.mapper.RestaurantMapper; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.RestaurantInfo; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.request.RestaurantCreateRequest; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dto.request.RestaurantUpdateRequest; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.exception.NotFoundRestaurantException; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class RestaurantService { + private final RestaurantRepository restaurantRepository; + private final RestaurantMapper mapper; + + public RestaurantInfo create(RestaurantCreateRequest request){ + Restaurant entity = Restaurant.builder() + .name(request.getName()) + .category(Category.valueOf(request.getCategory())) + .build(); + return mapper.mapEntityToInfo(restaurantRepository.save(entity)); + } + + public RestaurantInfo update(RestaurantUpdateRequest request) { + Restaurant foundRestaurant = restaurantRepository + .findById(request.getId()) + .orElseThrow(NotFoundRestaurantException::new); + foundRestaurant.update(mapper.mapUpdateRequestToInfo(request)); + return mapper.mapEntityToInfo(restaurantRepository.save(foundRestaurant)); + } + + @Transactional(readOnly = true) + public RestaurantPageInfo getRestaurantByPagination(int offset, int size) { + PageRequest pageRequest = PageRequest.of(offset, size); + Page restaurantByPagination = restaurantRepository.findRestaurantWithPagination(pageRequest); + return mapper.mapEntityToRestaurantPageInfo(restaurantByPagination); + } + + @Transactional(readOnly = true) + public RestaurantPageInfo getRestaurantByCategoryAndPagination(int offset, int size, Category category) { + PageRequest pageRequest = PageRequest.of(offset, size); + Page restaurantByPagination = restaurantRepository.findRestaurantWithCategoryAndPagination(category, pageRequest); + return mapper.mapEntityToRestaurantPageInfo(restaurantByPagination); + } + + @Transactional(readOnly = true) + public RestaurantInfo getOneRestaurant(Long id) { + Restaurant foundRestaurant = + restaurantRepository.findById(id) + .orElseThrow(NotFoundRestaurantException::new); + return mapper.mapEntityToInfo(foundRestaurant); + } + + public void delete(Long id) { + Restaurant foundRestaurant = + restaurantRepository.findById(id) + .orElseThrow(NotFoundRestaurantException::new); + foundRestaurant.delete(); + restaurantRepository.save(foundRestaurant); + } + +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/controller/ReviewController.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/controller/ReviewController.java new file mode 100644 index 00000000..2c66df3c --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/controller/ReviewController.java @@ -0,0 +1,53 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.controller; + +import com.techeer.goodnighthackathonspringboot.domain.review.dto.request.ReviewCreateRequest; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.ReviewInfo; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.request.ReviewUpdateRequest; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.response.ReviewPageInfo; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.response.ReviewResponse; +import com.techeer.goodnighthackathonspringboot.domain.review.service.ReviewService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +@RequestMapping("/api/v1/review") +@RestController +@RequiredArgsConstructor +public class ReviewController { + private final ReviewService reviewService; + + @PostMapping + public ResponseEntity write( + @Valid @RequestBody ReviewCreateRequest request + ){ + return ResponseEntity.ok(reviewService.create(request)); + } + + @PatchMapping + public ResponseEntity update(@Valid @RequestBody ReviewUpdateRequest request){ + System.out.println(request.toString()); + return ResponseEntity.ok(reviewService.update(request)); + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id){ + reviewService.delete(id); + return ResponseEntity.noContent().build(); + } + + @GetMapping("/{id}") + public ResponseEntity getOne(@PathVariable Long id){ + return ResponseEntity.ok(reviewService.getOne(id)); + } + + @GetMapping("/page") + public ResponseEntity getReviewByPagination( + @RequestParam(defaultValue = "0") int offset, + @RequestParam(defaultValue = "10") int size, + @RequestParam String cmd){ + ReviewPageInfo reviewPageInfo = reviewService.getReviewByPagination(offset, size, cmd); + return ResponseEntity.ok(reviewPageInfo); + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dao/ReviewRepository.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dao/ReviewRepository.java new file mode 100644 index 00000000..8d3cc041 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dao/ReviewRepository.java @@ -0,0 +1,16 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.dao; + +import com.techeer.goodnighthackathonspringboot.domain.review.domain.Review; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +public interface ReviewRepository extends JpaRepository { + @Query("select r from Review r where r.isActivated is true order by r.createOn asc") + Page findReviewWithPaginationOrderByCreatedOnAsc(Pageable pageable); + + @Query("select r from Review r where r.isActivated is true order by r.createOn desc") + Page findReviewWithPaginationOrderByCreatedOnDesc(Pageable pageable); + +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/domain/Review.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/domain/Review.java new file mode 100644 index 00000000..2d9f91c7 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/domain/Review.java @@ -0,0 +1,41 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.domain; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Restaurant; +import com.techeer.goodnighthackathonspringboot.global.domain.BaseEntity; +import lombok.*; + +import javax.persistence.*; + +@Entity +@Getter +@AllArgsConstructor +@NoArgsConstructor(access= AccessLevel.PROTECTED) +@Table(name = "review") +public class Review extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "restaurant_id", nullable = false) + private Restaurant restaurant; + + @Column(name = "title", nullable = false) + private String title; + + @Column(name = "contents", nullable = false) + private String contents; + + @Builder + public Review(Restaurant restaurant, String title, String contents) { + this.restaurant = restaurant; + this.title = title; + this.contents = contents; + this.isActivated = true; + } + + public void update(Restaurant restaurant, String title, String contents){ + this.restaurant = restaurant; + this.title = title; + this.contents = contents; + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/ReviewInfo.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/ReviewInfo.java new file mode 100644 index 00000000..e61ca18e --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/ReviewInfo.java @@ -0,0 +1,14 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.dto; + +import lombok.*; + +@Getter +@Builder +@AllArgsConstructor +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class ReviewInfo { + private Long id; + private Long restaurantId; + private String title; + private String contents; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/mapper/ReviewMapper.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/mapper/ReviewMapper.java new file mode 100644 index 00000000..5de60b34 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/mapper/ReviewMapper.java @@ -0,0 +1,29 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.dto.mapper; + +import com.techeer.goodnighthackathonspringboot.domain.review.domain.Review; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.ReviewInfo; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.response.ReviewPageInfo; +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class ReviewMapper { + + public ReviewInfo mapEntityToInfo(Review review){ + return ReviewInfo.builder() + .id(review.getId()) + .restaurantId(review.getRestaurant().getId()) + .title(review.getTitle()) + .contents(review.getContents()) + .build(); + } + + public ReviewPageInfo mapEntityToReviewPageInfo(Page reviewList) { + List reviewInfoList = + reviewList.stream().map(this::mapEntityToInfo).collect(Collectors.toList()); + return ReviewPageInfo.builder().reviewInfos(reviewInfoList).build(); + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/request/ReviewCreateRequest.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/request/ReviewCreateRequest.java new file mode 100644 index 00000000..f5951d64 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/request/ReviewCreateRequest.java @@ -0,0 +1,22 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.dto.request; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +@Builder +@AllArgsConstructor +@Getter +@RequiredArgsConstructor +public class ReviewCreateRequest { + @NotNull(message = "레스토랑 id는 필수입니다.") + private Long restaurantId; + @NotEmpty(message = "리뷰 타이틀은 필수입니다.") + private String title; + @NotEmpty(message = "리뷰 내용은 필수입니다.") + private String contents; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/request/ReviewUpdateRequest.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/request/ReviewUpdateRequest.java new file mode 100644 index 00000000..cdc8344e --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/request/ReviewUpdateRequest.java @@ -0,0 +1,24 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.dto.request; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Builder +@AllArgsConstructor +@Getter +@RequiredArgsConstructor +public class ReviewUpdateRequest { + @NotNull(message = "레스토랑 id는 필수입니다.") + private Long restaurantId; + @NotNull(message = "리뷰 id는 필수입니다.") + private Long id; + @NotBlank(message = "리뷰 제목은 필수입니다.") + private String title; + @NotBlank(message = "리뷰 내용은 필수입니다.") + private String contents; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/response/ReviewPageInfo.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/response/ReviewPageInfo.java new file mode 100644 index 00000000..dafa3434 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/response/ReviewPageInfo.java @@ -0,0 +1,17 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.dto.response; + +import com.techeer.goodnighthackathonspringboot.domain.review.dto.ReviewInfo; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Builder +@AllArgsConstructor +@Getter +@NoArgsConstructor +public class ReviewPageInfo { + private List reviewInfos; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/response/ReviewResponse.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/response/ReviewResponse.java new file mode 100644 index 00000000..2ab01978 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/dto/response/ReviewResponse.java @@ -0,0 +1,13 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.dto.response; + +import lombok.*; + +@Getter +@Builder +@AllArgsConstructor +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class ReviewResponse { + private String restaurantName; + private String title; + private String contents; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/exception/NotFoundReviewException.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/exception/NotFoundReviewException.java new file mode 100644 index 00000000..c4c217ab --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/exception/NotFoundReviewException.java @@ -0,0 +1,10 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.exception; + +import com.techeer.goodnighthackathonspringboot.global.error.ErrorCode; +import com.techeer.goodnighthackathonspringboot.global.exception.BusinessException; + +public class NotFoundReviewException extends BusinessException { + public NotFoundReviewException() { + super(ErrorCode.NOT_FOUND_RESTAURANT_ENTITY); + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/service/ReviewService.java b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/service/ReviewService.java new file mode 100644 index 00000000..30ed40ec --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/domain/review/service/ReviewService.java @@ -0,0 +1,76 @@ +package com.techeer.goodnighthackathonspringboot.domain.review.service; + +import com.techeer.goodnighthackathonspringboot.domain.restaurant.dao.RestaurantRepository; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.domain.Restaurant; +import com.techeer.goodnighthackathonspringboot.domain.restaurant.exception.NotFoundRestaurantException; +import com.techeer.goodnighthackathonspringboot.domain.review.dao.ReviewRepository; +import com.techeer.goodnighthackathonspringboot.domain.review.domain.Review; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.request.ReviewCreateRequest; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.ReviewInfo; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.request.ReviewUpdateRequest; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.mapper.ReviewMapper; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.response.ReviewPageInfo; +import com.techeer.goodnighthackathonspringboot.domain.review.dto.response.ReviewResponse; +import com.techeer.goodnighthackathonspringboot.domain.review.exception.NotFoundReviewException; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class ReviewService { + private final ReviewRepository reviewRepository; + private final RestaurantRepository restaurantRepository; + private final ReviewMapper mapper; + + public ReviewInfo create(ReviewCreateRequest request) { + Restaurant restaurant = restaurantRepository.findById(request.getRestaurantId()) + .orElseThrow(NotFoundRestaurantException::new); + Review review = Review.builder() + .restaurant(restaurant) + .title(request.getTitle()) + .contents(request.getContents()) + .build(); + return mapper.mapEntityToInfo(reviewRepository.save(review)); + } + + public ReviewInfo update(ReviewUpdateRequest request){ + Review review = reviewRepository.findById(request.getId()) + .orElseThrow(NotFoundReviewException::new); + Restaurant restaurant = restaurantRepository.findById(request.getRestaurantId()) + .orElseThrow(NotFoundRestaurantException::new); + review.update(restaurant, request.getTitle(), request.getContents()); + return mapper.mapEntityToInfo(reviewRepository.save(review)); + } + + public void delete(Long id){ + Review review = reviewRepository.findById(id).orElseThrow(NotFoundReviewException::new); + reviewRepository.delete(review); + } + + public ReviewResponse getOne(Long id){ + Review review = reviewRepository.findById(id) + .orElseThrow(NotFoundReviewException::new); + return ReviewResponse.builder() + .restaurantName(review.getRestaurant().getName()) + .title(review.getTitle()) + .contents(review.getContents()) + .build(); + } + + @Transactional(readOnly = true) + public ReviewPageInfo getReviewByPagination(int offset, int size, String cmd) { + if (cmd.equals("desc")) { + PageRequest pageRequest = PageRequest.of(offset, size); + Page reviewByPagination = reviewRepository.findReviewWithPaginationOrderByCreatedOnAsc(pageRequest); + return mapper.mapEntityToReviewPageInfo(reviewByPagination); + } + else { + PageRequest pageRequest = PageRequest.of(offset, size); + Page reviewByPagination = reviewRepository.findReviewWithPaginationOrderByCreatedOnDesc(pageRequest); + return mapper.mapEntityToReviewPageInfo(reviewByPagination); + } + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/global/config/JpaAuditingConfig.java b/src/main/java/com/techeer/goodnighthackathonspringboot/global/config/JpaAuditingConfig.java new file mode 100644 index 00000000..a2aa8c6b --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/global/config/JpaAuditingConfig.java @@ -0,0 +1,9 @@ +package com.techeer.goodnighthackathonspringboot.global.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@EnableJpaAuditing +@Configuration +public class JpaAuditingConfig { +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/global/domain/BaseEntity.java b/src/main/java/com/techeer/goodnighthackathonspringboot/global/domain/BaseEntity.java new file mode 100644 index 00000000..34af7946 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/global/domain/BaseEntity.java @@ -0,0 +1,29 @@ +package com.techeer.goodnighthackathonspringboot.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 abstract class BaseEntity { + @CreatedDate + private LocalDateTime createOn; + + @LastModifiedDate + private LocalDateTime updateOn; + + @Column(name = "is_activated", nullable = false) + protected boolean isActivated; + + public void activeOff(){ + this.isActivated = false; + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/global/error/ErrorCode.java b/src/main/java/com/techeer/goodnighthackathonspringboot/global/error/ErrorCode.java new file mode 100644 index 00000000..39c740bf --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/global/error/ErrorCode.java @@ -0,0 +1,22 @@ +package com.techeer.goodnighthackathonspringboot.global.error; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** Enum Naming Format : {주체}_{이유} message format: 동사 명사형으로 마무리 */ +@Getter +@AllArgsConstructor +public enum ErrorCode { + // Global + INTERNAL_SERVER_ERROR(500, "G001", "서버 오류"), + INPUT_INVALID_VALUE(400, "G002", "잘못된 입력"), + // Restaurant + NOT_FOUND_RESTAURANT_ENTITY(400, "R001", "존재하지 않는 restaurant 입니다."), + // Review + NOT_FOUND_REVIEW_ENTITY(400,"R101","존재하지 않는 review 입니다."), + ; + + private final int status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/global/error/ErrorResponse.java b/src/main/java/com/techeer/goodnighthackathonspringboot/global/error/ErrorResponse.java new file mode 100644 index 00000000..8d36d7d9 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/global/error/ErrorResponse.java @@ -0,0 +1,66 @@ +package com.techeer.goodnighthackathonspringboot.global.error; + +import lombok.*; +import org.springframework.validation.BindingResult; +import org.springframework.validation.FieldError; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Builder +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class ErrorResponse { + private String businessCode; + private String errorMessage; + private List errors; + + public ErrorResponse(ErrorCode code, List fieldErrors) { + this.errorMessage = code.getMessage(); + this.errors = fieldErrors; + this.businessCode = code.getCode(); + } + + private ErrorResponse(ErrorCode code) { + this.errorMessage = code.getMessage(); + this.businessCode = code.getCode(); + this.errors = new ArrayList<>(); + } + + public static ErrorResponse of(final ErrorCode code, final BindingResult bindingResult) { + return new ErrorResponse(code, FieldError.of(bindingResult)); + } + + public static ErrorResponse of(ErrorCode code) { + return new ErrorResponse(code); + } + + @Getter + @NoArgsConstructor(access = AccessLevel.PROTECTED) + public static class FieldError { + private String field; + private String value; + private String reason; + + public FieldError(final String field, final String value, final String reason) { + this.field = field; + this.value = value; + this.reason = reason; + } + + private static List of(final BindingResult bindingResult) { + final List fieldErrors = + bindingResult.getFieldErrors(); + return fieldErrors.stream() + .map( + error -> + new FieldError( + error.getField(), + error.getRejectedValue() == null ? "" : error.getRejectedValue().toString(), + error.getDefaultMessage())) + .collect(Collectors.toList()); + } + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/global/exception/BusinessException.java b/src/main/java/com/techeer/goodnighthackathonspringboot/global/exception/BusinessException.java new file mode 100644 index 00000000..2c6429f1 --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/global/exception/BusinessException.java @@ -0,0 +1,15 @@ +package com.techeer.goodnighthackathonspringboot.global.exception; + +import com.techeer.goodnighthackathonspringboot.global.error.ErrorCode; +import lombok.Getter; + +@Getter +public class BusinessException extends RuntimeException { + + private final ErrorCode errorCode; + + public BusinessException(ErrorCode errorCode) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + } +} diff --git a/src/main/java/com/techeer/goodnighthackathonspringboot/global/exception/handler/GlobalExceptionHandler.java b/src/main/java/com/techeer/goodnighthackathonspringboot/global/exception/handler/GlobalExceptionHandler.java new file mode 100644 index 00000000..294e166d --- /dev/null +++ b/src/main/java/com/techeer/goodnighthackathonspringboot/global/exception/handler/GlobalExceptionHandler.java @@ -0,0 +1,38 @@ +package com.techeer.goodnighthackathonspringboot.global.exception.handler; + +import com.techeer.goodnighthackathonspringboot.global.error.ErrorCode; +import com.techeer.goodnighthackathonspringboot.global.error.ErrorResponse; +import com.techeer.goodnighthackathonspringboot.global.exception.BusinessException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import static com.techeer.goodnighthackathonspringboot.global.error.ErrorCode.INPUT_INVALID_VALUE; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler + protected ResponseEntity handleRuntimeException(BusinessException e) { + final ErrorCode errorCode = e.getErrorCode(); + final ErrorResponse response = + ErrorResponse.builder() + .errorMessage(errorCode.getMessage()) + .businessCode(errorCode.getCode()) + .build(); + log.warn(e.getMessage()); + return ResponseEntity.status(errorCode.getStatus()).body(response); + } + + @ExceptionHandler + protected ResponseEntity handleMethodArgumentNotValidException( + MethodArgumentNotValidException e) { + final ErrorResponse response = ErrorResponse.of(INPUT_INVALID_VALUE, e.getBindingResult()); + log.warn(e.getMessage()); + return new ResponseEntity<>(response, BAD_REQUEST); + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 00000000..180e9ef2 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,17 @@ +#spring: +# datasource: +# url: jdbc:h2:~/dev +# driver-class-name: org.h2.Driver +# username: sa +# password: +# h2: +# console: +# enabled: true +# +# jpa: +# hibernate: +# ddl-auto: create +# properties: +# hibernate: +# format_sql: true +# show-sql: true \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..7b9c564c --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,12 @@ +spring: + jpa: + open-in-view: true + hibernate: + ddl-auto: create + naming: + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + use-new-id-generator-mappings: false + show-sql: true + properties: + hibernate.format_sql: true + dialect: org.hibernate.dialect.MySQL5InnoDBDialect \ No newline at end of file diff --git a/src/test/java/com/techeer/goodnighthackathonspringboot/GoodNightHackathonSpringBootApplicationTests.java b/src/test/java/com/techeer/goodnighthackathonspringboot/GoodNightHackathonSpringBootApplicationTests.java new file mode 100644 index 00000000..4fad6529 --- /dev/null +++ b/src/test/java/com/techeer/goodnighthackathonspringboot/GoodNightHackathonSpringBootApplicationTests.java @@ -0,0 +1,13 @@ +//package com.techeer.goodnighthackathonspringboot; +// +//import org.junit.jupiter.api.Test; +//import org.springframework.boot.test.context.SpringBootTest; +// +//@SpringBootTest +//class GoodNightHackathonSpringBootApplicationTests { +// +// @Test +// void contextLoads() { +// } +// +//}