diff --git a/week3/seungbeom/.gitignore b/week3/seungbeom/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/week3/seungbeom/.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/week3/seungbeom/README.md b/week3/seungbeom/README.md new file mode 100644 index 0000000..07e923a --- /dev/null +++ b/week3/seungbeom/README.md @@ -0,0 +1,43 @@ +## Spring Study 3주차 +### 학습 목표 +- 간단한 회원 생성, 조회 기능을 수행하는 API서버를 만들고 Spring의 전반적인 활용방법과 데이터베이스 연결 방법을 배운다. + +### 실습 과정 중 발생한 오류들! +*** +- H2 데이터베이스 설정 시 jdbc url을 지정해놓고 연결을 누르면 다음과 같은 오류가 발생. +![스크린샷 2024-09-18 205542](https://github.com/user-attachments/assets/4b5b32d9-50eb-4488-a959-d7128139e2bc) +- 자동으로 mv.db파일이 생기면서 연결이 가능해야 하지만 불가능했음. +- 결국 지정 경로에 직접 파일 생성 후 재연결 +![스크린샷 2024-09-18 205948](https://github.com/user-attachments/assets/48c50a97-bd61-4414-b8c4-74b339295fed) +- 성공!! +- 그리고 h2 데이터베이스를 실행하지 않고 스프링 프로젝트를 실행 시 데이터베이스를 연결하지 못했다는 에러를 볼 수 있으므로 +실행 전 h2 데이터베이스를 사전에 실행해 놓은 상태인지 확인! + +### 실습을 진행하면서 들었던 궁금증들! +*** +#### 1. 왜 Spring 에서는 프로젝트의 계층을 3가지(Controller, Service, Repository)로 나누어 개발하고 관리하는 것일까? +- 책임 분리를 통한 유지보수성을 높이기 위함! +- Controller는 요청과 응답에, Service는 비즈니스 로직에, Repository는 데이터베이스와의 상호작용에 집중하여 독립성을 올리고 결집도를 낮춘다. +- 책임 분리를 통해 각 계층의 부담을 줄이고 역할에 필요한 코드만을 간결하게 유지 +#### 2. 컨트롤러에서 데이터를 외부로 전달하고 받을 때 DTO형식을 사용하는 이유는 뭘까? +- 엔티티 자체만으로는 서비스 내 모든 로직들을 감당하기 어렵다. +- 각 요청에 맞는 데이터 양식들(PK값만 보내기, PK와 이름 OR 전체 데이터까지)을 모두 엔티티에 반영하면 복잡성이 증가하고 유지보수성이 떨어진다. +- 엔티티를 그대로 노출하게 되면 엔티티가 변경되었을 때 API 스펙 역시 변경되기 때문에 혼란이 발생할 수 있다. +#### 3. 웹 서비스 내에서 발생한 예외 처리는 어느 계층이 담당해야 할까? +- 일반적으로 Service 계층과 Controller 계층이 나누어 처리한다. +- Service 계층에서는 서비스 자체적으로 다루는 비즈니스 로직에서 발생하는 예외와 데이터베이스 처리 과정 중 발생한 예외를 예외 메서지와 상태 코드를 +Controller 계층으로 전달한다. +- Controller 계층에서는 Service 계층으로부터 넘겨받은 예외 정보를 바탕으로 적절한 HTTP 상태코드와 메세지를 클라이언트에게 전달한다. + +### API 테스트 화면 +*** +#### 1. 멤버 생성([POST] /members) +![스크린샷 2024-09-18 211240](https://github.com/user-attachments/assets/0f7249cb-70b4-4925-9160-eb96dc44e156) +#### 2. 전체 멤버 조회([GET] /members) +![스크린샷 2024-09-18 211352](https://github.com/user-attachments/assets/dad226f4-054b-4ff9-82e5-4efe974f58c7) +#### 2-1. 전체 멤버 조회 실패(데이터베이스에 멤버가 존재하지 않는 경우) +![스크린샷 2024-09-18 211729](https://github.com/user-attachments/assets/12609e4c-a4fc-4b24-8b54-9a89db6cf76f) +#### 3. 멤버 단건 조회([GET] /members/{memberId}) +![스크린샷 2024-09-18 211456](https://github.com/user-attachments/assets/eb118f1b-f3e6-4be0-b7e8-ec7b1f8a1359) +#### 3-1. 멤버 단건 조회 실패(없는 멤버의 pk를 쿼리 스트링으로 넘겼을 때) +![스크린샷 2024-09-18 211633](https://github.com/user-attachments/assets/a7aa19b7-cc98-4bde-b1d9-6b672fd5923e) \ No newline at end of file diff --git a/week3/seungbeom/build.gradle b/week3/seungbeom/build.gradle new file mode 100644 index 0000000..b25db66 --- /dev/null +++ b/week3/seungbeom/build.gradle @@ -0,0 +1,38 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.3' + id 'io.spring.dependency-management' version '1.1.6' +} + +group = 'Spring-Study' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/week3/seungbeom/gradle/wrapper/gradle-wrapper.jar b/week3/seungbeom/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/week3/seungbeom/gradle/wrapper/gradle-wrapper.jar differ diff --git a/week3/seungbeom/gradle/wrapper/gradle-wrapper.properties b/week3/seungbeom/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..0aaefbc --- /dev/null +++ b/week3/seungbeom/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/week3/seungbeom/gradlew b/week3/seungbeom/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/week3/seungbeom/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/week3/seungbeom/gradlew.bat b/week3/seungbeom/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/week3/seungbeom/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/week3/seungbeom/settings.gradle b/week3/seungbeom/settings.gradle new file mode 100644 index 0000000..0afd8de --- /dev/null +++ b/week3/seungbeom/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'mutsa-study' diff --git a/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/MutsaStudyApplication.java b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/MutsaStudyApplication.java new file mode 100644 index 0000000..59f8780 --- /dev/null +++ b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/MutsaStudyApplication.java @@ -0,0 +1,13 @@ +package Spring_Study.mutsa_study; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MutsaStudyApplication { + + public static void main(String[] args) { + SpringApplication.run(MutsaStudyApplication.class, args); + } + +} diff --git a/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/controller/MemberController.java b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/controller/MemberController.java new file mode 100644 index 0000000..abc1d75 --- /dev/null +++ b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/controller/MemberController.java @@ -0,0 +1,53 @@ +package Spring_Study.mutsa_study.controller; + +import Spring_Study.mutsa_study.domain.Member; +import Spring_Study.mutsa_study.dto.MemberRequestDTO; +import Spring_Study.mutsa_study.service.MemberService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/members") +public class MemberController { + + private final MemberService memberService; + + @PostMapping + public ResponseEntity createMember(@RequestBody MemberRequestDTO requestDTO) { + Member member = memberService.createMember(requestDTO); + return ResponseEntity.status(201).body(member); + } + + @GetMapping + public ResponseEntity getMemberList() { + try { + List members = memberService.findAllMembers(); + if (members.isEmpty()) { + return ResponseEntity.status(200).body("사용자가 존재하지 않습니다."); + } + return ResponseEntity.status(200).body(members); + }catch (Exception e) { + return ResponseEntity.status(500).body("서버 내부 에러"); + } + + } + + @GetMapping("/{memberId}") + public ResponseEntitygetOneMember(@PathVariable("memberId") Long memberId) { + try{ + Optional response = memberService.findMemberById(memberId); + if (response.isPresent()) { + return ResponseEntity.ok(response.get()); + } else { + return ResponseEntity.status(404).body("해당 사용자를 찾을 수 없습니다."); + } + }catch(Exception e){ + return ResponseEntity.status(500).body("서버 내부 에러"); + } + } +} diff --git a/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/domain/Member.java b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/domain/Member.java new file mode 100644 index 0000000..ba2d46a --- /dev/null +++ b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/domain/Member.java @@ -0,0 +1,28 @@ +package Spring_Study.mutsa_study.domain; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor +public class Member { + @Id + @GeneratedValue + @Column(name = "member_id") + private Long id; + + private String name; + private String email; + + @Builder + public Member(String name, String email) { + this.name = name; + this.email = email; + } +} diff --git a/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/dto/MemberRequestDTO.java b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/dto/MemberRequestDTO.java new file mode 100644 index 0000000..0752b1b --- /dev/null +++ b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/dto/MemberRequestDTO.java @@ -0,0 +1,21 @@ +package Spring_Study.mutsa_study.dto; + +import Spring_Study.mutsa_study.domain.Member; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class MemberRequestDTO { + private String name; + private String email; + + public Member toEntity() { + return Member.builder() + .email(email) + .name(name) + .build(); + } +} diff --git a/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/repository/MemberRepository.java b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/repository/MemberRepository.java new file mode 100644 index 0000000..15063b9 --- /dev/null +++ b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/repository/MemberRepository.java @@ -0,0 +1,7 @@ +package Spring_Study.mutsa_study.repository; + +import Spring_Study.mutsa_study.domain.Member; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MemberRepository extends JpaRepository { +} diff --git a/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/service/MemberService.java b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/service/MemberService.java new file mode 100644 index 0000000..2a13f36 --- /dev/null +++ b/week3/seungbeom/src/main/java/Spring_Study/mutsa_study/service/MemberService.java @@ -0,0 +1,32 @@ +package Spring_Study.mutsa_study.service; + +import Spring_Study.mutsa_study.domain.Member; +import Spring_Study.mutsa_study.dto.MemberRequestDTO; +import Spring_Study.mutsa_study.repository.MemberRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class MemberService { + private final MemberRepository memberRepository; + + @Transactional + public Member createMember(MemberRequestDTO requestDTO) { + Member member = memberRepository.save(requestDTO.toEntity()); + return member; + } + + public List findAllMembers() { + return memberRepository.findAll(); + } + + public Optional findMemberById(Long id) { + return memberRepository.findById(id); + } +} diff --git a/week3/seungbeom/src/main/resources/application.yml b/week3/seungbeom/src/main/resources/application.yml new file mode 100644 index 0000000..1262a8a --- /dev/null +++ b/week3/seungbeom/src/main/resources/application.yml @@ -0,0 +1,17 @@ +spring: + datasource: + url: jdbc:h2:tcp://localhost/~/study + username: sa + driver-class-name: org.h2.Driver + + jpa: + hibernate: + ddl-auto: create + properties: + hibernate: + format_sql: true + +logging: + level: + org.hibernate.SQL: debug + org.hibernate.orm.jdbc.bind: trace \ No newline at end of file diff --git a/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/Example.java b/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/Example.java new file mode 100644 index 0000000..3218b68 --- /dev/null +++ b/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/Example.java @@ -0,0 +1,13 @@ +package Spring_Study.mutsa_study; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class Example { + + @Test + void test() { + + } +} diff --git a/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/MutsaStudyApplicationTests.java b/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/MutsaStudyApplicationTests.java new file mode 100644 index 0000000..ad979f7 --- /dev/null +++ b/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/MutsaStudyApplicationTests.java @@ -0,0 +1,13 @@ +package Spring_Study.mutsa_study; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MutsaStudyApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/controller/MemberControllerTest.java b/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/controller/MemberControllerTest.java new file mode 100644 index 0000000..877e463 --- /dev/null +++ b/week3/seungbeom/src/test/java/Spring_Study/mutsa_study/controller/MemberControllerTest.java @@ -0,0 +1,105 @@ +package Spring_Study.mutsa_study.controller; + +import Spring_Study.mutsa_study.domain.Member; +import Spring_Study.mutsa_study.dto.MemberRequestDTO; +import Spring_Study.mutsa_study.repository.MemberRepository; +import Spring_Study.mutsa_study.service.MemberService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +public class MemberControllerTest { + @Autowired + protected MockMvc mvc; + + @Autowired + protected ObjectMapper objectMapper; + + @Autowired + protected WebApplicationContext webApplicationContext; + + @Autowired + MemberRepository memberRepository; + @Autowired + private MemberService memberService; + + @BeforeEach + public void mockMvcSetup() { + this.mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .build(); + memberRepository.deleteAll(); + } + + @Test + public void addMember() throws Exception { + final String url = "/members"; + final String name = "박승범"; + final String email = "psb3707@naver.com"; + final MemberRequestDTO requestDTO = new MemberRequestDTO(name, email); + + final String requestBody = objectMapper.writeValueAsString(requestDTO); + ResultActions resultActions = mvc.perform(post(url) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(requestBody)); + + resultActions.andExpect(status().isCreated()); + List members = memberRepository.findAll(); + assertThat(members.size()).isEqualTo(1); + assertThat(members.get(0).getName()).isEqualTo(name); + assertThat(members.get(0).getEmail()).isEqualTo(email); + } + + @DisplayName("getMembers() : 멤버 전체 조회에 성공한다.") + @Test + public void getMembers() throws Exception { + final String url = "/members"; + + memberService.createMember(new MemberRequestDTO("박승범", "psb3707@naver.com")); + memberService.createMember(new MemberRequestDTO("박준범", "pjb3707@naver.com")); + + ResultActions resultActions = mvc.perform(get(url) + .accept(MediaType.APPLICATION_JSON_VALUE)); + + resultActions.andExpect(status().isOk()) + .andExpect(jsonPath("$[0].name").value("박승범")) + .andExpect(jsonPath("$[0].email").value("psb3707@naver.com")) + .andExpect(jsonPath("$[1].name").value("박준범")) + .andExpect(jsonPath("$[1].email").value("pjb3707@naver.com")); + } + + @DisplayName("getMember() : 멤버 단건 조회에 성공한다.") + @Test + public void getMember() throws Exception { + final String url = "/members/{id}"; + + Member member = memberService.createMember(new MemberRequestDTO("박승범", "psb3707@naver.com")); + + ResultActions result = mvc.perform(get(url, member.getId()) + .accept(MediaType.APPLICATION_JSON_VALUE)); + + result.andExpect(status().isOk()) + .andExpect(jsonPath("$.email").value("psb3707@naver.com")) + .andExpect(jsonPath("$.name").value("박승범")); + } +} \ No newline at end of file