diff --git a/week02/minji/cb1/Dockerfile b/week02/minji/cb1/Dockerfile new file mode 100644 index 0000000..5b7398d --- /dev/null +++ b/week02/minji/cb1/Dockerfile @@ -0,0 +1,14 @@ +FROM ubuntu:latest +LABEL authors="jo791" + +ENTRYPOINT ["top", "-b"] + +# openjdk11를 베이스로 이미지를 생성한다. +FROM openjdk:11 +# JAR_FILE에 jar 빌드 파일이 있는 경로를 저장한다 +ARG JAR_FILE=build/libs/*.jar +# jar 빌드 파일을 도커 컨테이너 안 app.jar 이름으로 복사 +COPY ${JAR_FILE} app.jar +# 컨테이너가 실행 될 때 실행되는 명령어 +# 컨테이너가 실행되면 jar 파일을 실행한다. +ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/week02/minji/cb1/src/main/java/com/example/cb1/api/BoardController.java b/week02/minji/cb1/src/main/java/com/example/cb1/api/BoardController.java index 26f0cd3..bbe70f2 100644 --- a/week02/minji/cb1/src/main/java/com/example/cb1/api/BoardController.java +++ b/week02/minji/cb1/src/main/java/com/example/cb1/api/BoardController.java @@ -8,7 +8,7 @@ import java.util.List; @RestController -@RequestMapping("/boards") +@RequestMapping("/board") public class BoardController { @Autowired diff --git a/week02/minji/cb1/src/main/java/com/example/cb1/domain/Board.java b/week02/minji/cb1/src/main/java/com/example/cb1/domain/Board.java index b9bbfc0..92f222a 100644 --- a/week02/minji/cb1/src/main/java/com/example/cb1/domain/Board.java +++ b/week02/minji/cb1/src/main/java/com/example/cb1/domain/Board.java @@ -11,7 +11,7 @@ @Getter @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) -@Table(name = "boards") +@Table(name = "board") public class Board { @Id diff --git a/week03/.idea/.gitignore b/week03/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/week03/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/week03/.idea/compiler.xml b/week03/.idea/compiler.xml new file mode 100644 index 0000000..a9df587 --- /dev/null +++ b/week03/.idea/compiler.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/week03/.idea/gradle.xml b/week03/.idea/gradle.xml new file mode 100644 index 0000000..59972f5 --- /dev/null +++ b/week03/.idea/gradle.xml @@ -0,0 +1,16 @@ + + + + + + \ No newline at end of file diff --git a/week03/.idea/jarRepositories.xml b/week03/.idea/jarRepositories.xml new file mode 100644 index 0000000..fdc392f --- /dev/null +++ b/week03/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/week03/.idea/misc.xml b/week03/.idea/misc.xml new file mode 100644 index 0000000..2a9b4c1 --- /dev/null +++ b/week03/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/week03/.idea/modules.xml b/week03/.idea/modules.xml new file mode 100644 index 0000000..68fb649 --- /dev/null +++ b/week03/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/week03/.idea/vcs.xml b/week03/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/week03/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/week03/.idea/week03.iml b/week03/.idea/week03.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/week03/.idea/week03.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/week03/minji/dbendpagination/.gitignore b/week03/minji/dbendpagination/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/week03/minji/dbendpagination/.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/week03/minji/dbendpagination/build.gradle b/week03/minji/dbendpagination/build.gradle new file mode 100644 index 0000000..8d10053 --- /dev/null +++ b/week03/minji/dbendpagination/build.gradle @@ -0,0 +1,37 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.7.16' + id 'io.spring.dependency-management' version '1.0.15.RELEASE' +} + +group = 'com.codingbottle' +version = '0.0.1-SNAPSHOT' + +java { + 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' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + 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/week03/minji/dbendpagination/gradle/wrapper/gradle-wrapper.jar b/week03/minji/dbendpagination/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..033e24c Binary files /dev/null and b/week03/minji/dbendpagination/gradle/wrapper/gradle-wrapper.jar differ diff --git a/week03/minji/dbendpagination/gradle/wrapper/gradle-wrapper.properties b/week03/minji/dbendpagination/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9f4197d --- /dev/null +++ b/week03/minji/dbendpagination/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/week03/minji/dbendpagination/gradlew b/week03/minji/dbendpagination/gradlew new file mode 100644 index 0000000..fcb6fca --- /dev/null +++ b/week03/minji/dbendpagination/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/week03/minji/dbendpagination/gradlew.bat b/week03/minji/dbendpagination/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/week03/minji/dbendpagination/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/week03/minji/dbendpagination/settings.gradle b/week03/minji/dbendpagination/settings.gradle new file mode 100644 index 0000000..0b8f9f7 --- /dev/null +++ b/week03/minji/dbendpagination/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'dbendpagination' diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/DbendpaginationApplication.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/DbendpaginationApplication.java new file mode 100644 index 0000000..9fad7e4 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/DbendpaginationApplication.java @@ -0,0 +1,13 @@ +package com.codingbottle.dbendpagination; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DbendpaginationApplication { + + public static void main(String[] args) { + SpringApplication.run(DbendpaginationApplication.class, args); + } + +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/common/PageInfoDto.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/common/PageInfoDto.java new file mode 100644 index 0000000..b180048 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/common/PageInfoDto.java @@ -0,0 +1,36 @@ +package com.codingbottle.dbendpagination.api.common; + +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import org.springframework.data.domain.Page; + +@Getter +@Builder(access = AccessLevel.PRIVATE) +public class PageInfoDto { + + int currentPage; // 현재 페이지 번호 + int size; // 페이지당 기본 사이즈 + boolean hasNext; // 다음 페이지 존재 여부 + boolean hasPrevious; // 이전 페이지 존재 여부 + boolean isFirst; // 첫번째 페이지 여부 + boolean isLast; // 마지막 페이지 여부 + int numberOfElements; // 현재 페이지의 데이터 수 + + long totalElements; // 전체 데이터 수 + int totalPages; // 전체 페이지 수 + + public static PageInfoDto from(Page page) { + return PageInfoDto.builder() + .currentPage(page.getNumber() + 1) // zero-based index이므로 1을 더해줌 + .size(page.getSize()) + .hasNext(page.hasNext()) + .hasPrevious(page.hasPrevious()) + .isFirst(page.isFirst()) + .isLast(page.isLast()) + .numberOfElements(page.getNumberOfElements()) + .totalElements(page.getTotalElements()) + .totalPages(page.getTotalPages()) + .build(); + } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/common/RspTemplate.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/common/RspTemplate.java new file mode 100644 index 0000000..79e054d --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/common/RspTemplate.java @@ -0,0 +1,23 @@ +package com.codingbottle.dbendpagination.api.common; + +import lombok.Getter; +import org.springframework.http.HttpStatus; + +// 응답 템플릿 +@Getter +public class RspTemplate { + int statusCode; + String message; + T data; + + public RspTemplate(HttpStatus httpStatus, String message, T data) { + this.statusCode = httpStatus.value(); + this.message = message; + this.data = data; + } + + public RspTemplate(HttpStatus httpStatus, String message) { + this.statusCode = httpStatus.value(); + this.message = message; + } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/student/controller/StudentController.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/student/controller/StudentController.java new file mode 100644 index 0000000..975d036 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/student/controller/StudentController.java @@ -0,0 +1,87 @@ +package com.codingbottle.dbendpagination.api.student.controller; + +import com.codingbottle.dbendpagination.api.common.RspTemplate; +import com.codingbottle.dbendpagination.api.student.dto.StudentListRspDto; +import com.codingbottle.dbendpagination.domain.student.Student; +import com.codingbottle.dbendpagination.domain.student.StudentService; +import com.codingbottle.dbendpagination.global.util.PageableUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RequiredArgsConstructor +@RestController +public class StudentController { + private final StudentService studentService; + + /** + * 4. + * 어떻게 하냐? Spring Data JPA에서 자동화해줌. pageable + * + * pageable을 Spring Data Jpa Repository method의 파라미터로 전달하는 것만으로 페이지네이션 쿼리가 가능 + * pageable을 전달한 메서드의 반환값은 Page or Slice임 + * Page란? 침하하. 전체 용량을 알아야 하고, count query가 필요함 + * Slice란? 당근마켓. 전체 용량을 알 필요 없음. 현재 페이지가 끝인지 아닌지만 알면 됨. count query 필요없음 + * 불필요한 count query가 날라가지 않게끔, slice로 가능하면 Slice를 쓰는게 좋음. + * + * 그래서 Page extends Slice + * extends 이해하기 - 확장(extend)이라고 이해하자.. 딸 extends 아빠 하면 군대가야함 + * + * 페이지네이션 예시(Slice랑 Page 둘다)를 보고, + * 메인쿼리 카운트쿼리 날아가는거 보기. + */ + // select ... from ... offset 10 limit 10 + // 100개 있을 때 10~19번째 데이터를 가져옴. + // 이 작업을 간단하게 처리할 수 있게 도와주는 것이 Spring Data JPA에서 제공하는 Pageable 객체. + + // student 객체의 목록을 반환할 것. + // 데이터를 어디서부터 몇 개 가져올건지를 클라이언트 개발자. 가 지정하게 할 것. + // 1. 한 페이지의 사이즈 10개 <- 이건 서버에서 정합시다. + // 2. 몇 페이지인데? 2 페이지 <- 이것만 클라이언트에서 지정하게. + @GetMapping("/students") + public RspTemplate handleGetAllStudents( + @RequestParam(defaultValue = "1") int page + ) { + // 내가 반환하고 싶은 것: 학생Id, 이름 - StudentListRspDto + + // Pageable 객체의 구현체 PageRequest 가 필요하다 + final int DEFAULT_PAGE_SIZE = 10; + Pageable pageable = PageableUtil.of(page, DEFAULT_PAGE_SIZE); + + // Student List를 Service에서 가져온다. + Page studentPage = studentService.findAll(pageable); + // StudentListRspDto.from(students)를 통해 Dto의 리스트로 변환해서 반환한다. + StudentListRspDto studentListRspDto = StudentListRspDto.from(studentPage); + + return new RspTemplate<>(HttpStatus.OK + , page + "번 페이지 조회 완료" + , studentListRspDto + ); + } + +// @GetMapping("/students-slice") +// public RspTemplate handleGetAllStudentsS( +// @RequestParam(defaultValue = "1") int page +// ) { +// // 내가 반환하고 싶은 것: 학생Id, 이름 - StudentListRspDto +// +// // Pageable 객체의 구현체 PageRequest 가 필요하다 +// final int DEFAULT_PAGE_SIZE = 10; +// Pageable pageable = PageableUtil.of(page, DEFAULT_PAGE_SIZE); +// +// // Student List를 Service에서 가져온다. +// Slice studentPage = studentService.findAllSlice(pageable); +// // StudentListRspDto.from(students)를 통해 Dto의 리스트로 변환해서 반환한다. +// StudentListRspDto studentListRspDto = StudentListRspDto.from(studentPage); +// +// return new RspTemplate<>(HttpStatus.OK +// , page + "번 페이지 조회 완료" +// , studentListRspDto +// ); +// } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/student/dto/StudentListRspDto.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/student/dto/StudentListRspDto.java new file mode 100644 index 0000000..669f243 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/student/dto/StudentListRspDto.java @@ -0,0 +1,49 @@ +package com.codingbottle.dbendpagination.api.student.dto; + + +import com.codingbottle.dbendpagination.api.common.PageInfoDto; +import com.codingbottle.dbendpagination.domain.student.Student; +import lombok.Builder; +import lombok.Getter; +import org.springframework.data.domain.Page; + +import java.util.List; +import java.util.stream.Collectors; + +@Getter +public class StudentListRspDto { + // id, name의 목록 + List students; + PageInfoDto pageInfo; + + public static StudentListRspDto from(Page students) { + List studentDtoList = StudentDto.from(students); + PageInfoDto pageInfoDto = PageInfoDto.from(students); + return new StudentListRspDto(studentDtoList, pageInfoDto); + } + + private StudentListRspDto(List students, PageInfoDto pageInfo) { + this.students = students; + this.pageInfo = pageInfo; + } + + @Getter + @Builder + static class StudentDto { + long id; + String name; + + static StudentDto from(Student student) { + return StudentDto.builder() + .id(student.getId()) + .name(student.getName()) + .build(); + } + + static List from(Page students) { + return students.stream() + .map(student -> StudentDto.from(student)) + .collect(Collectors.toList()); + } + } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/studentinlecture/controller/StudentInLectureController.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/studentinlecture/controller/StudentInLectureController.java new file mode 100644 index 0000000..ae93b5e --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/studentinlecture/controller/StudentInLectureController.java @@ -0,0 +1,179 @@ +package com.codingbottle.dbendpagination.api.studentinlecture.controller; + +import com.codingbottle.dbendpagination.api.common.RspTemplate; +import com.codingbottle.dbendpagination.api.studentinlecture.dto.PenaltyReqDto; +import com.codingbottle.dbendpagination.domain.studentinlecture.Penalty; +import com.codingbottle.dbendpagination.domain.studentinlecture.StudentInLecture; +import com.codingbottle.dbendpagination.domain.studentinlecture.StudentInLectureService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +/** // 백엔드 애플리케이션 개발을 위한 최소 역량 ? + * // 우리의 취업전선 경쟁자는 스스로 공부를 하는 사람들!!! + * + * // '스프링 부트' 라는 이름이 있는 책이나 강의 사서 배우면 좋아요. + * + * 1. 스프링 기초 이론 (의존성 주입, 빈 컨테이너(IOC Container), thread per request) + * 2. DB 기초 이론 (적어도 간단한 join문 작성 가능하고, 트랜잭션이 왜 존재하는 건지 알고 있음) + * 3. JPA 이론 (persistence context 의 1차 캐시, 스냅샷, DB flush 타이밍 등의 개념 'JPA 김영한씨 책' ) + * 4. HTTP 기초 (HTTP Method들의 의미, 자주 사용되는 상태코드와 그것의 의미, 자주 사용되는 HTTP Header의 사용예시, SOP-CORS 이해) + * 5. 개발 프로세스에 대한 경험과 감각 (언어 숙련도, 가독성-재사용성 좋은 코드 짜기, 빈틈없는 코드를 짜고 테스트 잘 하기) + */ +@RequiredArgsConstructor +@RestController +public class StudentInLectureController { + private final StudentInLectureService studentInLectureService; + + /** + * 1. 수강신청 API 만들기 + * url - 계층구조. + * url - [POST] /student-in-lectures/lectures/1/students/1 + *

+ * 그럼 StudentInLecture 객체 생성해서 저장 가능 + * penaltyState는 NONE + */ + // 수강신청 + // studentId는 사실 일반적인 경우 넣을 필요가 없는데 + // 아직 저희가 '인증' 을 배우지 않아서 그러함. + @PostMapping("/student-in-lectures/lectures/{lectureId}/students/{studentId}") + // handler method + public RspTemplate handleCreateStudentInLecture( + @PathVariable Long lectureId, @PathVariable Long studentId + ) { + // 수강신청 객체 StudentInLecture를 생성해서 repo 객체의 save() 호출에서 저장하는 것이 목적. + // lectureId, studentId 로 강의와 학생을 파악 가능. + // service 계층을 호출해서 객체 생성. + long savedStuInLecId = studentInLectureService.create(lectureId, studentId); + + return new RspTemplate<>(HttpStatus.OK + , savedStuInLecId + "번 수강신청 완료" + ); +// return ResponseEntity +// // "/student-in-lectures/{savedStuInLecId}" 로 [GET] 요청을 보내면 방금 만든 데이터 보내준다는 의미. +// .created(URI.create("/student-in-lectures/" + savedStuInLecId)) +// .build(); + } + + /** + * 2. 벌점부여 API 만들기 + * 원데이 클래스라고 가정함 + * n주차 이런 거 없음 + * n주차를 구현하려면 테이블을 하나 더 만들었을 것 같음 + *

+ * url : /student-in-lecture/1 // 여기서 이미 어떤 강의 어떤 학생인지가 정해져있음. + * PATCH PUT + * body: 벌점(지각, 결석 ENUM) + */ + + //수정 전 벌점 api +// @PatchMapping("/student-in-lectures/{studentInLectureId}") +// public RspTemplate handleUpdateStudentInLecture( +// @PathVariable Long studentInLectureId +// , @RequestBody PenaltyReqDto reqDto +// ) { +// // 1. '벌점'을 의미하는 요청값( json 형식) 을 받아서 StudentInLecture 객체를 update한다. +// Penalty penalty = reqDto.getPenalty(); +// long updatedStuInLecId = studentInLectureService.updatePenalty(studentInLectureId, penalty); +// +// return new RspTemplate<>(HttpStatus.OK +// , updatedStuInLecId + "번 수강신청의 벌점이 수정되었습니다."); +// } + + //수정 후 벌점 api + @PatchMapping("/student-in-lectures/{studentInLectureId}") + public RspTemplate handleUpdateStudentInLecture( + @PathVariable Long studentInLectureId, + @RequestBody PenaltyReqDto reqDto + ) { + // 1. '벌점'을 의미하는 요청값(json 형식)을 받아서 StudentInLecture 객체를 update한다. + Penalty penalty = reqDto.getPenalty(); + + // 2. StudentInLecture 객체를 찾아온다. + StudentInLecture studentInLecture = studentInLectureService.getById(studentInLectureId); + + // 3. 학생의 총 벌점을 가져온다. + int totalPenalty = studentInLecture.getStudent().getTotalPenalty(); + + // 4. 이전 벌점 정보를 가져온다. + Penalty previousPenalty = Penalty.NONE; + if (studentInLecture.getPenalty() != null) { + previousPenalty = Penalty.values()[studentInLecture.getPenalty()]; + } + + // 5. 학생의 벌점을 업데이트한다. + totalPenalty -= previousPenalty.getValue(); // 이전 벌점 감산 + totalPenalty += penalty.getValue(); // 새로운 벌점 누적 + studentInLecture.getStudent().setTotalPenalty(totalPenalty); + + // 6. StudentInLecture 객체의 벌점을 변경한다. + studentInLecture.setPenalty(penalty); + + // 7. StudentInLecture를 저장하고 업데이트된 정보를 반환한다. + studentInLectureService.updatePenalty(studentInLectureId, penalty); + + return new RspTemplate<>(HttpStatus.OK, + studentInLectureId + "번 수강신청의 벌점이 수정되었습니다. 현재 총 벌점: " + totalPenalty + "점"); + } + + + /** + * **과제** + * + * 3. 요구사항 추가. 벌점부여 API 수정. + * + * 학생 자체의 벌점을 기록해야 함. + * DB상의 특정 컬럼이 해당 학생의 총 벌점을 나타내야 한다는 것! (예시: Student 객체에 Integer totalPenalty 필드) + * + * @PatchMapping("/student-in-lectures/{studentInLectureId}") + * 로 요청이 들어올 때, + * + * student 객체의 벌점 점수 (totalPenalty)를 누적해야 한다. + * + * 같은 요청을 여러 번 보내면, 두 번째 요청부터는 벌점이 덮어쓰기 형식으로 진행. + * + * 하나의 studentInLecture 를 대상으로 + * 결석으로 벌점을 수정하는 요청을 N번 보내면 + * 벌점이 10 + 10 + 10 = 30이 되는 것이 아니라 + * + * 10으로 고정되어있어야 함. + * + * 10 2 0 + * 0 + * + * 학생1로 강의1, 2에 모두 수강신청을 해서 + * id 1, 2를 가진 studentInLecture 데이터가 생성되었다고 가정. + * + * @PatchMapping("/student-in-lectures/1")에 + * '결석' 벌점부과 요청을 보내면 + * 학생1의 totalPenalty는 10점이 되어야 한다. (0 + 10 = 10) + * + * 이후 @PatchMapping("/student-in-lectures/2")에 + * '지각' 벌점부과 요청을 보내면 + * 학생1의 totalPenalty는 12점이 되어야 한다. (10 + 2 = 12) + * + * 그런데 처음 벌점부과 요청은 관리자의 실수였다고 한다! + * 다시 @PatchMapping("/student-in-lectures/1") 로 + * '없음' 벌점부과 요청을 보내면 + * '결석' 처리가 '없음' 으로 변경되어서 + * 학생1의 totalPenalty는 2점이 되어야 한다. (12 - 10 = 2) + */ + + /** + * 5. + * Fetch Join + 페이징 + * 특정 강좌를 듣고 있는 학생의 목록 출력해야 함 + * Lecture는 ByID()로 따로 조회하고 + * StudentInLecture Fetch Student Where Lecture.id = lectureId + * + * Fetch Join 왜하냐? + * 데이터를 다룰 때는 보수적으로 가는 게 좋음 + * 전체 Eager - 필요할 때 Lazy는 그런 방법이 없을 뿐더러 예측이 힘듬 + * 전체 Lazy - 필요할 때 Eager(Fetch Join)이 관리가 쉬움 + */ + + + + + +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/studentinlecture/dto/PenaltyReqDto.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/studentinlecture/dto/PenaltyReqDto.java new file mode 100644 index 0000000..c41f83f --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/api/studentinlecture/dto/PenaltyReqDto.java @@ -0,0 +1,11 @@ +package com.codingbottle.dbendpagination.api.studentinlecture.dto; + +import com.codingbottle.dbendpagination.domain.studentinlecture.Penalty; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +public class PenaltyReqDto { // 역직렬화 + Penalty penalty; +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/Lecture.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/Lecture.java new file mode 100644 index 0000000..1dcf45c --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/Lecture.java @@ -0,0 +1,46 @@ +package com.codingbottle.dbendpagination.domain.lecture; + +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +public class Lecture { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + + @Builder + private Lecture(String name) { + this.name = name; + } +} + + + + + + + + + + + + + + + + + + + + + diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/LectureRepository.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/LectureRepository.java new file mode 100644 index 0000000..77a5a94 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/LectureRepository.java @@ -0,0 +1,6 @@ +package com.codingbottle.dbendpagination.domain.lecture; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface LectureRepository extends JpaRepository { +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/LectureService.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/LectureService.java new file mode 100644 index 0000000..4f9d19c --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/lecture/LectureService.java @@ -0,0 +1,23 @@ +package com.codingbottle.dbendpagination.domain.lecture; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@RequiredArgsConstructor +@Transactional(readOnly = true) +@Service +public class LectureService { + private final LectureRepository lectureRepository; + + public Lecture getById(Long lectureId) { + Optional optionalLecture = lectureRepository.findById(lectureId); + + if (optionalLecture.isEmpty()) { + throw new IllegalArgumentException("해당 강의가 존재하지 않습니다."); + } + return optionalLecture.get(); + } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/Student.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/Student.java new file mode 100644 index 0000000..2b28b86 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/Student.java @@ -0,0 +1,47 @@ +package com.codingbottle.dbendpagination.domain.student; + +import lombok.*; + +import javax.persistence.*; + +@Getter +@Setter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +public class Student { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + + //왜 이 컬럼에는 not null이 안될까요? 이 어노테이션을 넣으면 error발생.. + //@Column(nullable = false) + private Integer totalPenalty; + + @Builder + private Student(String name) { + this.name = name; + } + + + +} + + + + + + + + + + + + + + + + + diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/StudentRepository.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/StudentRepository.java new file mode 100644 index 0000000..6f764e9 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/StudentRepository.java @@ -0,0 +1,6 @@ +package com.codingbottle.dbendpagination.domain.student; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface StudentRepository extends JpaRepository { +} \ No newline at end of file diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/StudentService.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/StudentService.java new file mode 100644 index 0000000..b203e58 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/student/StudentService.java @@ -0,0 +1,32 @@ +package com.codingbottle.dbendpagination.domain.student; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@RequiredArgsConstructor +@Transactional(readOnly = true) +@Service +public class StudentService { + private final StudentRepository studentRepository; + + public Student getById(Long studentId) { + return studentRepository.findById(studentId) + .orElseThrow(() -> new IllegalArgumentException("해당 학생이 존재하지 않습니다.")); + } + + public Page findAll(Pageable pageable) { + // List + // Page + return studentRepository.findAll(pageable); + } + + public Slice findAllSlice(Pageable pageable) { + // List + // Page + return studentRepository.findAll(pageable); + } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/Penalty.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/Penalty.java new file mode 100644 index 0000000..66294a2 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/Penalty.java @@ -0,0 +1,16 @@ +package com.codingbottle.dbendpagination.domain.studentinlecture; + + +import lombok.Getter; + +@Getter +public enum Penalty { + // 없음, 지각, 결석 + NONE(0), LATE(2), ABSENT(10); + + private final int value; + + Penalty(int value) { + this.value = value; + } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLecture.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLecture.java new file mode 100644 index 0000000..ff057f3 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLecture.java @@ -0,0 +1,60 @@ +package com.codingbottle.dbendpagination.domain.studentinlecture; + +import com.codingbottle.dbendpagination.domain.lecture.Lecture; +import com.codingbottle.dbendpagination.domain.student.Student; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Entity +public class StudentInLecture { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // 어떤 학생이 어떤 강의를 듣는지에 대한 정보. + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "student_id", nullable = false) + private Student student; + + // 연관 객체가 필요할 때만 EAGER로 가져오게 하는 방법 + // FETCH JOIN + + // EAGER로 깔아둔 다음에, 필요할 때만 LAZY + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "lecture_id", nullable = false) + private Lecture lecture; + + private Integer penalty; + + public void setPenalty(Penalty penalty) { + this.penalty = penalty.getValue(); + } + + @Builder + private StudentInLecture(Student student, Lecture lecture) { + this.student = student; + this.lecture = lecture; + this.penalty = Penalty.NONE.getValue(); + } +} + + + + + + + + + + + + + + diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLectureRepository.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLectureRepository.java new file mode 100644 index 0000000..6900173 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLectureRepository.java @@ -0,0 +1,6 @@ +package com.codingbottle.dbendpagination.domain.studentinlecture; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface StudentInLectureRepository extends JpaRepository { +} \ No newline at end of file diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLectureService.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLectureService.java new file mode 100644 index 0000000..d820440 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/domain/studentinlecture/StudentInLectureService.java @@ -0,0 +1,75 @@ +package com.codingbottle.dbendpagination.domain.studentinlecture; + +import com.codingbottle.dbendpagination.domain.lecture.Lecture; +import com.codingbottle.dbendpagination.domain.lecture.LectureService; +import com.codingbottle.dbendpagination.domain.student.Student; +import com.codingbottle.dbendpagination.domain.student.StudentService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@RequiredArgsConstructor +@Transactional(readOnly = true) +@Service +public class StudentInLectureService { + private final StudentInLectureRepository studentInLectureRepository; + private final StudentService studentService; + private final LectureService lectureService; + + @Transactional + public long create(Long lectureId, Long studentId) { + + // 1. id로 연관 객체(student, lecture)를 찾는다. + // Persistence Context (1차 저장소) 에 등록. + Lecture lecture = lectureService.getById(lectureId); + Student student = studentService.getById(studentId); + + // 2. 연관 객체를 찾으면 StudentInLecture 객체를 생성하고 저장한다. + StudentInLecture studentInLecture = StudentInLecture.builder() + .student(student) + .lecture(lecture) + .build(); + + // 1차 저장소에 등록 + StudentInLecture savedStuInLec = studentInLectureRepository.save(studentInLecture); + return savedStuInLec.getId(); + // 메서드를 종료한 직후, 1차 저장소의 변경사항을 DB에 flush 처리하고, + // 트랜잭션을 commit; + } + + @Transactional + public long updatePenalty(Long studentInLectureId, Penalty penalty) { + // 2. studentInLectureId 라는 경로 변수로 StudentInLecture 객체를 찾아온다. + StudentInLecture studentInLecture = getById(studentInLectureId); + + // 3. 이전 벌점 정보를 가져온다. + Penalty previousPenalty = Penalty.NONE; // 기본값으로 설정 + if (studentInLecture.getPenalty() != null) { + // studentInLecture.getPenalty()의 값이 null이 아닐 때만 변환을 시도하도록 변경 + previousPenalty = Penalty.values()[studentInLecture.getPenalty()]; + } + + // 4. studentInLecture 객체의 벌점을 변경한다. + studentInLecture.setPenalty(penalty); + + // 5. 학생의 총 벌점을 업데이트한다. + int updatedTotalPenalty = studentInLecture.getStudent().getTotalPenalty(); + updatedTotalPenalty -= previousPenalty.getValue(); // 이전 벌점 감산 + updatedTotalPenalty += penalty.getValue(); // 새로운 벌점 누적 + studentInLecture.getStudent().setTotalPenalty(updatedTotalPenalty); + + return studentInLecture.getId(); + // 1차 저장소의 정보가 DB로 flush 되고, 트랜잭션이 commit 된다. + } + + public StudentInLecture getById(Long studentInLectureId) { + Optional optionalStudentInLecture = studentInLectureRepository.findById(studentInLectureId); + if (optionalStudentInLecture.isEmpty()) { + throw new IllegalArgumentException("해당 수강신청이 존재하지 않습니다."); + } + + return optionalStudentInLecture.get(); + } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/global/util/InitDB.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/global/util/InitDB.java new file mode 100644 index 0000000..40ac68a --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/global/util/InitDB.java @@ -0,0 +1,48 @@ +package com.codingbottle.dbendpagination.global.util; + + +import com.codingbottle.dbendpagination.domain.lecture.Lecture; +import com.codingbottle.dbendpagination.domain.lecture.LectureRepository; +import com.codingbottle.dbendpagination.domain.student.Student; +import com.codingbottle.dbendpagination.domain.student.StudentRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.PostConstruct; + +@RequiredArgsConstructor +@Component +public class InitDB { + private final StudentRepository studentRepository; + private final LectureRepository lectureRepository; + // 애플리케이션 실행 시점에 빈 컨테이너에 단 하나의 객체(스프링 빈)을 등록해요 + + @Transactional + @PostConstruct + public void init() { + Lecture java = Lecture.builder() + .name("자바") + .build(); + Lecture cpp = Lecture.builder() + .name("C++") + .build(); + lectureRepository.save(java); lectureRepository.save(cpp); + + Student kim = Student.builder() + .name("김코딩") + .build(); + Student jung = Student.builder() + .name("정코딩") + .build(); + + int studentCount = 100; + for (int i = 0; i < studentCount; i+=1) { + Student student = Student.builder() + .name(i + "학생") + .build(); + studentRepository.save(student); + } + studentRepository.save(kim); studentRepository.save(jung); + } +} diff --git a/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/global/util/PageableUtil.java b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/global/util/PageableUtil.java new file mode 100644 index 0000000..b2b4d00 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/java/com/codingbottle/dbendpagination/global/util/PageableUtil.java @@ -0,0 +1,30 @@ +package com.codingbottle.dbendpagination.global.util; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class PageableUtil { + + /** 0-base인 페이지를 클라이언트단에서 1-based인 것처럼 사용할 수 있게 한다. + * @param oneBasedPage + * @param size + * @return 0-based pageable Instance + */ + public static Pageable of(int oneBasedPage, int size) { + if (oneBasedPage < 1) + throw new IllegalArgumentException("page는 1 이상이어야 합니다."); + + return PageRequest.of(oneBasedPage - 1 , size); + } + + public static Pageable of(int oneBasedPage, int size, Sort sort) { + if (oneBasedPage < 1) + throw new IllegalArgumentException("page는 1 이상이어야 합니다."); + + return PageRequest.of(oneBasedPage - 1 , size, sort); + } +} diff --git a/week03/minji/dbendpagination/src/main/resources/application.properties b/week03/minji/dbendpagination/src/main/resources/application.properties new file mode 100644 index 0000000..3454495 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/resources/application.properties @@ -0,0 +1,11 @@ +spring.datasource.url=jdbc:mysql://localhost:3306/cbweek2 +spring.datasource.username=root +spring.datasource.password=1234 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.jpa.hibernate.ddl-auto=create +spring.jpa.database=mysql +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.default_batch_fetch_size=1000 +spring.jpa.show-sql=true +spring.jpa.open-in-view=false +logging.level.org.hibernate.type=TRACE diff --git a/week03/minji/dbendpagination/src/main/resources/db.md b/week03/minji/dbendpagination/src/main/resources/db.md new file mode 100644 index 0000000..03897a7 --- /dev/null +++ b/week03/minji/dbendpagination/src/main/resources/db.md @@ -0,0 +1,3 @@ +- CREATE DATABASE cbweek2 + CHARACTER SET utf8mb4 + COLLATE utf8mb4_unicode_ci; (case insensitive) \ No newline at end of file diff --git a/week03/minji/dbendpagination/src/test/java/com/codingbottle/dbendpagination/DbendpaginationApplicationTests.java b/week03/minji/dbendpagination/src/test/java/com/codingbottle/dbendpagination/DbendpaginationApplicationTests.java new file mode 100644 index 0000000..b280ff7 --- /dev/null +++ b/week03/minji/dbendpagination/src/test/java/com/codingbottle/dbendpagination/DbendpaginationApplicationTests.java @@ -0,0 +1,13 @@ +package com.codingbottle.dbendpagination; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DbendpaginationApplicationTests { + + @Test + void contextLoads() { + } + +}