diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..ddc5ac8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# Ensure consistent line endings +* text=auto + +# Define LF for specific file types +*.java text eol=lf +*.properties text eol=lf +*.md text eol=lf +*.gradle text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..97b4ceb --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ +.git +target +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/ + +### MYSQL ### +mysql/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4ed9631 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +FROM openjdk:17-jdk-slim as builder +WORKDIR /app + +COPY gradlew . +COPY gradle gradle +COPY build.gradle . +COPY settings.gradle . +COPY src src + +RUN ./gradlew build #--no-daemon +# 멀티 스테이지 빌드 사용 + +FROM openjdk:17-jdk-slim +LABEL maintainer="leesy010504" +EXPOSE 8080 +WORKDIR /app + +# 빌드 단계에서 생성된 JAR 파일 복사 +COPY --from=builder /app/build/libs/*.jar /first-docker-spring.jar + +# 애플리케이션 실행 +ENTRYPOINT ["java", "-jar", "/first-docker-spring.jar"] diff --git a/README.md b/README.md deleted file mode 100644 index 20270b2..0000000 --- a/README.md +++ /dev/null @@ -1,21 +0,0 @@ -![스프링 부트 프로젝트](https://images.velog.io/images/falling_star3/post/7eef0696-76c6-4dcb-858b-f91ef597eddc/스프링부트.JPG) - -1. **과제 내용** - * 🔧 로컬 데이터 베이스와 JPA를 연동한 스프링 부트 프로젝트를 만드는 실습입니다! - * 🚀 프로젝트 초기 구축은 [start.spring.io](https://start.spring.io/) 사이트를 사용하시면 됩니다. - * 📂 해당 레포지토리를 클론한 후 각자의 브랜치에서 작업 후 main 브랜치로 PR을 올려주세요! - * 🔍 포스트맨(Postman)을 통해 API 접근(로컬 환경)을 확인해주시고 노션에 결과를 남겨주세요. - - -2. **제출 기한** - * 🕛 **7월 11일 목요일 19시까지** 완료해 주시면 됩니다. - -------- - - - -### 📝 PR 및 리뷰 방법(중요!!) -* PR을 통해 리뷰를 진행할 예정입니다. -* 개인 레포지토리에 원본 레포지토리를 Fork한 후 원본 레포지토리 main 브랜치에 PR을 올리시거나 -* 원본 레포지토리의 다른 브랜치에서 작업 후 main 브랜치로 PR을 올려주세요. -* main 브랜치에 수정 사항으로 PR이 올라와 있다면 리뷰가 가능하므로 어떤 방법이든 상관없습니다! diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..b571c49 --- /dev/null +++ b/build.gradle @@ -0,0 +1,31 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.0' + id 'io.spring.dependency-management' version '1.1.5' +} + +group = 'PKNU' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-starter' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'mysql:mysql-connector-java:8.0.33' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +// implementation 'org.springframework.boot:spring-boot-devtools' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0dc1a2c --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,33 @@ +version: '3.8' +services: + db: + container_name: mysql + image: mysql:8.0.33 + ports: + - "3306:3306" + environment: + MYSQL_ROOT_PASSWORD: 1234 #추후 문서나 kubernetes secret등으로 민감정보 보관 예정 + MYSQL_DATABASE: mydatabase + TZ: Asia/Seoul + volumes: + - ./mysql:/var/lib/mysql + restart: always + + app: + build: + context: . + dockerfile: Dockerfile + container_name: first_spring_app + volumes: + - ./src:/app/src + - ./build:/app/build + ports: + - "8081:8080" + environment: + SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/mydatabase?serverTimezone=Asia/Seoul + SPRING_DATASOURCE_USERNAME: root + SPRING_DATASOURCE_PASSWORD: 1234 + depends_on: + - db + command: ./gradlew bootRun + restart: always \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 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 0000000..b82aa23 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && 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=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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/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. 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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..cf31b05 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'first-spring' diff --git a/src/main/java/PKNU/first_spring/FirstSpringApplication.java b/src/main/java/PKNU/first_spring/FirstSpringApplication.java new file mode 100644 index 0000000..2e69457 --- /dev/null +++ b/src/main/java/PKNU/first_spring/FirstSpringApplication.java @@ -0,0 +1,13 @@ +package PKNU.first_spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FirstSpringApplication { + + public static void main(String[] args) { + SpringApplication.run(FirstSpringApplication.class, args); + } + +} diff --git a/src/main/java/PKNU/first_spring/SpringConfig.java b/src/main/java/PKNU/first_spring/SpringConfig.java new file mode 100644 index 0000000..fae9142 --- /dev/null +++ b/src/main/java/PKNU/first_spring/SpringConfig.java @@ -0,0 +1,36 @@ +//package PKNU.first_spring; +// +//import PKNU.first_spring.repository.*; +//import PKNU.first_spring.service.CourseService; +//import PKNU.first_spring.service.MemberService; +//import PKNU.first_spring.service.QuizService; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +// +//@Configuration +//public class SpringConfig { +// @Bean +// public MemberService memberService() { +// return new MemberService(memberRepository()); +// } +// +// @Bean +// public MemberRepository memberRepository() { +// return new JpaMemberRepository(); +// } +// +// @Bean +// public CourseRepository courseRepository() { +// return new JpaCourseRepository(); +// } +// +// @Bean +// public CourseService courseService() { +// return new CourseService(memberRepository()); +// } +// +// @Bean +// public QuizService quizService() { +// return new QuizService(); +// } +//} diff --git a/src/main/java/PKNU/first_spring/controller/CourseController.java b/src/main/java/PKNU/first_spring/controller/CourseController.java new file mode 100644 index 0000000..bd82e57 --- /dev/null +++ b/src/main/java/PKNU/first_spring/controller/CourseController.java @@ -0,0 +1,45 @@ +package PKNU.first_spring.controller; + +import PKNU.first_spring.domain.Course; +import PKNU.first_spring.dto.CourseForm; +import PKNU.first_spring.service.CourseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/course") +public class CourseController { + private final CourseService courseService; + + @Autowired + public CourseController(CourseService courseService) { + this.courseService = courseService; + } + + @PostMapping("/addCourse") + public ResponseEntity createCourse(@RequestBody CourseForm form) { + Course course = new Course(); + course.setCourse_name(form.course_name()); + course.setInstructor(form.instructor()); + course.setScore(form.score()); + + return ResponseEntity.ok(courseService.addCourse(course)); + } + + @GetMapping + public ResponseEntity ListOfCourse(Model model){ + List courses = courseService.findCourses(); + + return ResponseEntity.ok(courses); + } + + @DeleteMapping("/deleteCourse") + public ResponseEntity deleteCourse(@RequestBody CourseForm form){ + courseService.deleteCourse(form.course_name()); + return ResponseEntity.ok("The course has been successfully deleted"); + } +} diff --git a/src/main/java/PKNU/first_spring/controller/EnrollmentController.java b/src/main/java/PKNU/first_spring/controller/EnrollmentController.java new file mode 100644 index 0000000..4159925 --- /dev/null +++ b/src/main/java/PKNU/first_spring/controller/EnrollmentController.java @@ -0,0 +1,35 @@ +package PKNU.first_spring.controller; +import PKNU.first_spring.domain.Enrollment; +import PKNU.first_spring.domain.Student; +import PKNU.first_spring.service.EnrollmentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/enrollment") +public class EnrollmentController { + EnrollmentService enrollmentService; + @Autowired + public EnrollmentController(EnrollmentService enrollmentService) { + this.enrollmentService = enrollmentService; + } + + @PostMapping("/{student-id}/{course-id}") + public ResponseEntity addEnrollment(@PathVariable("student-id") Long studentId, @PathVariable("course-id") Long courseId) { + Enrollment enrollment = enrollmentService.addEnrollment(studentId, courseId); + return ResponseEntity.ok(enrollment); + } + + @DeleteMapping("/{student-id}/{course-id}") + public void deleteEnrollment(@PathVariable("student-id") Long studentId, @PathVariable("course-id") Long courseId) { + enrollmentService.deleteEnrollmentById(studentId, courseId); + } + + @GetMapping("/{course-name}") + public ResponseEntity> getEnrollmentsByCourse(@PathVariable("course-name") String courseName) { + return ResponseEntity.ok(enrollmentService.getEnrollmentsByCourse(courseName)); + } +} diff --git a/src/main/java/PKNU/first_spring/controller/HomeController.java b/src/main/java/PKNU/first_spring/controller/HomeController.java new file mode 100644 index 0000000..87145a8 --- /dev/null +++ b/src/main/java/PKNU/first_spring/controller/HomeController.java @@ -0,0 +1,13 @@ +package PKNU.first_spring.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class HomeController { + + @GetMapping("/") + public String home() { + return "home"; + } +} diff --git a/src/main/java/PKNU/first_spring/controller/StudentController.java b/src/main/java/PKNU/first_spring/controller/StudentController.java new file mode 100644 index 0000000..07ff505 --- /dev/null +++ b/src/main/java/PKNU/first_spring/controller/StudentController.java @@ -0,0 +1,46 @@ +package PKNU.first_spring.controller; + +import PKNU.first_spring.domain.Student; +import PKNU.first_spring.dto.StudentForm; +import PKNU.first_spring.service.StudentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/student") +public class StudentController { + private final StudentService studentService; + + @Autowired + public StudentController(StudentService studentService) { + this.studentService = studentService; + } + + @PostMapping("/addStudent") + public ResponseEntity createStudent(@RequestBody StudentForm form) { + Student student = new Student(); + student.setName(form.student_name()); + student.setEmail(form.email()); + student.setBirth_date(form.birth_date()); + + studentService.join(student); + return ResponseEntity.ok("The student has been successfully created"); + } + + @GetMapping + public ResponseEntity List(Model model){ + List students = studentService.findStudents(); + + return ResponseEntity.ok(students); + } + + @DeleteMapping("/deleteStudent") + public ResponseEntity deleteStudent(@RequestBody StudentForm form){ + studentService.deleteStudent(form.student_name()); + return ResponseEntity.ok("The student has been successfully deleted"); + } +} diff --git a/src/main/java/PKNU/first_spring/domain/Course.java b/src/main/java/PKNU/first_spring/domain/Course.java new file mode 100644 index 0000000..b35533f --- /dev/null +++ b/src/main/java/PKNU/first_spring/domain/Course.java @@ -0,0 +1,51 @@ +package PKNU.first_spring.domain; + +import jakarta.persistence.*; +@Entity +@Table(name = "Course") +public class Course { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long course_id; + + @Column(name = "course_name") + private String course_name; + + @Column + private String instructor; + + @Column + private int Score; + + public String getInstructor() { + return instructor; + } + + public void setInstructor(String instructor) { + this.instructor = instructor; + } + + public Long getCourse_id() { + return course_id; + } + + public void setCourse_id(Long course_id) { + this.course_id = course_id; + } + + public String getCourse_name() { + return course_name; + } + + public void setCourse_name(String course_name) { + this.course_name = course_name; + } + + public int getScore() { + return Score; + } + + public void setScore(int score) { + Score = score; + } +} diff --git a/src/main/java/PKNU/first_spring/domain/Enrollment.java b/src/main/java/PKNU/first_spring/domain/Enrollment.java new file mode 100644 index 0000000..8f85dcf --- /dev/null +++ b/src/main/java/PKNU/first_spring/domain/Enrollment.java @@ -0,0 +1,55 @@ +package PKNU.first_spring.domain; + +import jakarta.persistence.*; + +import java.time.LocalDateTime; + +@Entity +public class Enrollment { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long enrollment_id; + + @Column + private LocalDateTime enrollment_date; + + @ManyToOne + @JoinColumn(name="student_id", referencedColumnName = "student_id") + Student student; + + @ManyToOne + @JoinColumn(name="course_id", referencedColumnName = "course_id") + Course course; + + public Student getStudent() { + return student; + } + + public void setStudent(Student student) { + this.student = student; + } + + public Course getCourse() { + return course; + } + + public void setCourse(Course course) { + this.course = course; + } + + public LocalDateTime getEnrollment_date() { + return enrollment_date; + } + + public void setEnrollment_date(LocalDateTime enrollment_date) { + this.enrollment_date = enrollment_date; + } + + public Long getEnrollment_id() { + return enrollment_id; + } + + public void setEnrollment_id(Long enrollment_id) { + this.enrollment_id = enrollment_id; + } +} diff --git a/src/main/java/PKNU/first_spring/domain/Student.java b/src/main/java/PKNU/first_spring/domain/Student.java new file mode 100644 index 0000000..ffa7cbf --- /dev/null +++ b/src/main/java/PKNU/first_spring/domain/Student.java @@ -0,0 +1,66 @@ +package PKNU.first_spring.domain; + +import jakarta.persistence.*; + +import java.util.Date; + +@Entity +public class Student { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column + private Long student_id; + + @Column + private String student_name; + + @Column + private String email; + + @Column + private Date birth_date; + + public Date getBirth_date() { + return birth_date; + } + + public void setBirth_date(Date birth_date) { + this.birth_date = birth_date; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getStudent_name() { + return student_name; + } + + public void setStudent_name(String student_name) { + this.student_name = student_name; + } + + public boolean sameName(String name) { + return this.student_name.equals(name); + } + + public String getName() { + return student_name; + } + + public void setName(String name) { + this.student_name = name; + } + + public Long getId() { + return student_id; + } + + public void setId(Long id) { + this.student_id = id; + } +} diff --git a/src/main/java/PKNU/first_spring/dto/CourseForm.java b/src/main/java/PKNU/first_spring/dto/CourseForm.java new file mode 100644 index 0000000..ee2ad65 --- /dev/null +++ b/src/main/java/PKNU/first_spring/dto/CourseForm.java @@ -0,0 +1,4 @@ +package PKNU.first_spring.dto; + +public record CourseForm(String course_name, String instructor, int score) { +} diff --git a/src/main/java/PKNU/first_spring/dto/EnrollmentForm.java b/src/main/java/PKNU/first_spring/dto/EnrollmentForm.java new file mode 100644 index 0000000..0193d27 --- /dev/null +++ b/src/main/java/PKNU/first_spring/dto/EnrollmentForm.java @@ -0,0 +1,6 @@ +package PKNU.first_spring.dto; + +import java.util.Date; + +public record EnrollmentForm(Date enrollment_date) { +} diff --git a/src/main/java/PKNU/first_spring/dto/StudentForm.java b/src/main/java/PKNU/first_spring/dto/StudentForm.java new file mode 100644 index 0000000..d4814e9 --- /dev/null +++ b/src/main/java/PKNU/first_spring/dto/StudentForm.java @@ -0,0 +1,6 @@ +package PKNU.first_spring.dto; + +import java.util.Date; + +public record StudentForm(String student_name, String email, Date birth_date) { +} diff --git a/src/main/java/PKNU/first_spring/repository/CourseRepository.java b/src/main/java/PKNU/first_spring/repository/CourseRepository.java new file mode 100644 index 0000000..6c20eab --- /dev/null +++ b/src/main/java/PKNU/first_spring/repository/CourseRepository.java @@ -0,0 +1,14 @@ +package PKNU.first_spring.repository; + +import PKNU.first_spring.domain.Course; + +import java.util.List; +import java.util.Optional; + +public interface CourseRepository { + Course saveCourse(Course course); + void deleteCourse(Course course); + Optional findByName(String name); + Optional findById(Long id); + List findAll(); +} diff --git a/src/main/java/PKNU/first_spring/repository/EnrollmentRepository.java b/src/main/java/PKNU/first_spring/repository/EnrollmentRepository.java new file mode 100644 index 0000000..d69b8ca --- /dev/null +++ b/src/main/java/PKNU/first_spring/repository/EnrollmentRepository.java @@ -0,0 +1,12 @@ +package PKNU.first_spring.repository; + +import PKNU.first_spring.domain.Enrollment; +import PKNU.first_spring.domain.Student; + +import java.util.List; + +public interface EnrollmentRepository { + List findStudentInCourse(String courseName); + Enrollment addEnrollment(Enrollment enrollment); + void deleteEnrollment(Enrollment enrollment); +} diff --git a/src/main/java/PKNU/first_spring/repository/JpaCourseRepository.java b/src/main/java/PKNU/first_spring/repository/JpaCourseRepository.java new file mode 100644 index 0000000..5d5fda2 --- /dev/null +++ b/src/main/java/PKNU/first_spring/repository/JpaCourseRepository.java @@ -0,0 +1,55 @@ +package PKNU.first_spring.repository; + +import PKNU.first_spring.domain.Course; +import jakarta.persistence.EntityManager; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; +@Repository +public class JpaCourseRepository implements CourseRepository { + + EntityManager em; + + public JpaCourseRepository(EntityManager em) { + this.em = em; + } + + @Override + public Course saveCourse(Course course) { + em.persist(course); + return course; + } + + @Override + public void deleteCourse(Course course) { + if (em.contains(course)) { + em.remove(course); + } else { + Course managedCourse = em.merge(course); + em.remove(managedCourse); + } + } + + @Override + public Optional findByName(String name) { + List result = em.createQuery("SELECT c FROM Course c WHERE c.course_name = :name", Course.class) + .setParameter("name", name) + .getResultList(); + return result.stream().findAny(); + } + + @Override + public Optional findById(Long id) { + List result = em.createQuery("SELECT c FROM Course c WHERE c.course_id = :id", Course.class) + .setParameter("id", id) + .getResultList(); + return result.stream().findAny(); + } + + @Override + public List findAll() { + return em.createQuery("SELECT c FROM Course c", Course.class) + .getResultList(); + } +} diff --git a/src/main/java/PKNU/first_spring/repository/JpaEnrollmentRepository.java b/src/main/java/PKNU/first_spring/repository/JpaEnrollmentRepository.java new file mode 100644 index 0000000..b69f1c4 --- /dev/null +++ b/src/main/java/PKNU/first_spring/repository/JpaEnrollmentRepository.java @@ -0,0 +1,43 @@ +package PKNU.first_spring.repository; + +import PKNU.first_spring.domain.Course; +import PKNU.first_spring.domain.Enrollment; +import PKNU.first_spring.domain.Student; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public class JpaEnrollmentRepository implements EnrollmentRepository { + + EntityManager em; + + public JpaEnrollmentRepository(EntityManager em) { + this.em = em; + } + + @Override + public Enrollment addEnrollment(Enrollment enrollment) { + em.persist(enrollment); + return enrollment; + } + + @Override + public void deleteEnrollment(Enrollment enrollment) { + if (em.contains(enrollment)) { + em.remove(enrollment); + } else { + Enrollment managedEnrollment = em.merge(enrollment); + em.remove(managedEnrollment); + } + } + + @Override + public List findStudentInCourse(String courseName) { + TypedQuery query = em.createQuery("select e.student FROM Enrollment e where e.course.course_name = :courseName", Student.class); + query.setParameter("courseName", courseName); + return query.getResultList(); + } +} diff --git a/src/main/java/PKNU/first_spring/repository/JpaStudentRepository.java b/src/main/java/PKNU/first_spring/repository/JpaStudentRepository.java new file mode 100644 index 0000000..26b3773 --- /dev/null +++ b/src/main/java/PKNU/first_spring/repository/JpaStudentRepository.java @@ -0,0 +1,55 @@ +package PKNU.first_spring.repository; + +import PKNU.first_spring.domain.Student; +import jakarta.persistence.EntityManager; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; +@Repository +public class JpaStudentRepository implements StudentRepository { + + EntityManager em; + + public JpaStudentRepository(EntityManager em) { + this.em = em; + } + + @Override + public Student save(Student student) { + em.persist(student); + return null; + } + + @Override + public void deleteStudent(Student student) { + if (em.contains(student)) { + em.remove(student); + } else { + Student managedStudent = em.merge(student); + em.remove(managedStudent); + } + } + + @Override + public Optional findByName(String name) { + List result = em.createQuery("SELECT s FROM Student s WHERE s.student_name = :name", Student.class) + .setParameter("name", name) + .getResultList(); + return result.stream().findAny(); + } + + @Override + public Optional findById(Long id) { + List result = em.createQuery("SELECT s FROM Student s WHERE s.student_id = :id", Student.class) + .setParameter("id", id) + .getResultList(); + return result.stream().findAny(); + } + + @Override + public List findAll() { + return em.createQuery("SELECT c FROM Student c", Student.class) + .getResultList(); + } +} diff --git a/src/main/java/PKNU/first_spring/repository/StudentRepository.java b/src/main/java/PKNU/first_spring/repository/StudentRepository.java new file mode 100644 index 0000000..f256113 --- /dev/null +++ b/src/main/java/PKNU/first_spring/repository/StudentRepository.java @@ -0,0 +1,14 @@ +package PKNU.first_spring.repository; + +import PKNU.first_spring.domain.Student; + +import java.util.List; +import java.util.Optional; + +public interface StudentRepository { + Student save(Student student); + void deleteStudent(Student student); + Optional findByName(String name); + Optional findById(Long id); + List findAll(); +} diff --git a/src/main/java/PKNU/first_spring/service/CourseService.java b/src/main/java/PKNU/first_spring/service/CourseService.java new file mode 100644 index 0000000..dce2de5 --- /dev/null +++ b/src/main/java/PKNU/first_spring/service/CourseService.java @@ -0,0 +1,31 @@ +package PKNU.first_spring.service; + +import PKNU.first_spring.domain.Course; +import PKNU.first_spring.repository.CourseRepository; +import jakarta.transaction.Transactional; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Transactional +@Service +public class CourseService { + private final CourseRepository courseRepository; + + public CourseService(CourseRepository courseRepository) { + this.courseRepository = courseRepository; + } + + public Course addCourse(Course course) { + return courseRepository.saveCourse(course); + } + + public void deleteCourse(String name){ + Course course = courseRepository.findByName(name).get(); + courseRepository.deleteCourse(course); + } + + public List findCourses() { + return courseRepository.findAll(); + } +} diff --git a/src/main/java/PKNU/first_spring/service/EnrollmentService.java b/src/main/java/PKNU/first_spring/service/EnrollmentService.java new file mode 100644 index 0000000..dc84462 --- /dev/null +++ b/src/main/java/PKNU/first_spring/service/EnrollmentService.java @@ -0,0 +1,51 @@ +package PKNU.first_spring.service; + +import PKNU.first_spring.domain.Course; +import PKNU.first_spring.domain.Enrollment; +import PKNU.first_spring.domain.Student; +import PKNU.first_spring.repository.CourseRepository; +import PKNU.first_spring.repository.EnrollmentRepository; +import PKNU.first_spring.repository.StudentRepository; +import jakarta.transaction.Transactional; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Transactional +@Service +public class EnrollmentService { + private final EnrollmentRepository enrollmentRepository; + private final StudentRepository studentRepository; + private final CourseRepository courseRepository; + + public EnrollmentService(EnrollmentRepository enrollmentRepository, StudentRepository studentRepository, CourseRepository courseRepository) { + this.enrollmentRepository = enrollmentRepository; + this.studentRepository = studentRepository; + this.courseRepository = courseRepository; + } + + public Enrollment isExist(Long student_id, Long course_id){ + Student student = studentRepository.findById(student_id) + .orElseThrow(() -> new IllegalArgumentException("Student not found")); + Course course = courseRepository.findById(course_id) + .orElseThrow(() -> new IllegalArgumentException("Course not found")); + + Enrollment enrollment = new Enrollment(); + enrollment.setStudent(student); + enrollment.setCourse(course); + + return enrollment; + } + + public Enrollment addEnrollment(Long student_id, Long course_id) { + return enrollmentRepository.addEnrollment(isExist(student_id, course_id)); + } + + public void deleteEnrollmentById(Long student_id, Long course_id) { + enrollmentRepository.deleteEnrollment(isExist(student_id, course_id)); + } + + public List getEnrollmentsByCourse(String courseName) { + return enrollmentRepository.findStudentInCourse(courseName); + } +} diff --git a/src/main/java/PKNU/first_spring/service/StudentService.java b/src/main/java/PKNU/first_spring/service/StudentService.java new file mode 100644 index 0000000..b908d91 --- /dev/null +++ b/src/main/java/PKNU/first_spring/service/StudentService.java @@ -0,0 +1,31 @@ +package PKNU.first_spring.service; + +import PKNU.first_spring.domain.Student; +import PKNU.first_spring.repository.StudentRepository; +import jakarta.transaction.Transactional; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Transactional +@Service +public class StudentService { + private final StudentRepository studentRepository; + + public StudentService(StudentRepository studentRepository) { + this.studentRepository = studentRepository; + } + + public void join(Student student) { + studentRepository.save(student); + } + + public void deleteStudent(String name){ + Student student = studentRepository.findByName(name).get(); + studentRepository.deleteStudent(student); + } + + public List findStudents() { + return studentRepository.findAll(); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..1641b5a --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,19 @@ +spring.application.name=first-spring +spring.mvc.hiddenmethod.filter.enabled=true + +spring.datasource.url=jdbc:mysql://db:3306/mydatabase?serverTimezone=Asia/Seoul +spring.datasource.username=root +spring.datasource.password=1234 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect + + +#Devtools? ??? auto restart +#spring.devtools.restart.enabled = true +#spring.devtools.restart.additional-exclude = static/**,public/** +# +#spring.devtools.livereload.enabled=true +#spring.freemarker.cache=false \ No newline at end of file diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html new file mode 100644 index 0000000..4b086b7 --- /dev/null +++ b/src/main/resources/templates/home.html @@ -0,0 +1,11 @@ + + + +
+
+

QUIZ!

+

Simple Quiz

+
+
+ + \ No newline at end of file diff --git a/src/test/java/PKNU/first_spring/DBTest/DbTest.java b/src/test/java/PKNU/first_spring/DBTest/DbTest.java new file mode 100644 index 0000000..92537d0 --- /dev/null +++ b/src/test/java/PKNU/first_spring/DBTest/DbTest.java @@ -0,0 +1,30 @@ +/* +package PKNU.first_spring.DBTest; + +import PKNU.first_spring.domain.Student; +import PKNU.first_spring.repository.StudentRepository; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +public class DbTest { + + @Autowired + private StudentRepository studentRepository; + + @Test + public void testDatabaseConnection() { + Student student = new Student(); + student.setName("Test Student"); + studentRepository.save(student); + + Optional foundStudent = studentRepository.findById(student.getId()); + assertThat(foundStudent).isPresent(); + assertThat(foundStudent.get().getName()).isEqualTo("Test Student"); + } +}*/ diff --git a/src/test/java/PKNU/first_spring/FirstSpringApplicationTests.java b/src/test/java/PKNU/first_spring/FirstSpringApplicationTests.java new file mode 100644 index 0000000..0eccf5d --- /dev/null +++ b/src/test/java/PKNU/first_spring/FirstSpringApplicationTests.java @@ -0,0 +1,15 @@ +/* +package PKNU.first_spring; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class FirstSpringApplicationTests { + + @Test + void contextLoads() { + } + +} +*/ diff --git a/src/test/java/PKNU/first_spring/repository/MemoryMemberRepositoryTest.java b/src/test/java/PKNU/first_spring/repository/MemoryMemberRepositoryTest.java new file mode 100644 index 0000000..cd27b44 --- /dev/null +++ b/src/test/java/PKNU/first_spring/repository/MemoryMemberRepositoryTest.java @@ -0,0 +1,53 @@ +/* +package PKNU.first_spring.repository; + +import PKNU.first_spring.domain.Member; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +class MemoryMemberRepositoryTest { + MemoryMemberRepository repository = new MemoryMemberRepository(); + + @AfterEach + public void afterEach(){ + repository.clearStore(); + } + + @Test + public void deleteOne(){ + Member member1 = new Member(); + member1.setName("spring1"); + Member member2 = new Member(); + member2.setName("spring2"); + repository.save(member1); + repository.save(member2); + + List result = repository.findAll(); + System.out.println("result = " + result); + + repository.deleteMember(member1); + + List result2 = repository.findAll(); + System.out.println("result = " + result2); + } + + @Test + public void findAll(){ + Member member2 = new Member(); + member2.setName("spring2"); + Member member4 = new Member(); + member4.setName("spring4"); + + repository.save(member2); + repository.save(member4); + + List result = repository.findAll(); + System.out.println("result = " + result); + + } +} +*/ diff --git a/src/test/java/PKNU/first_spring/service/MemberServiceTest.java b/src/test/java/PKNU/first_spring/service/MemberServiceTest.java new file mode 100644 index 0000000..ca693e7 --- /dev/null +++ b/src/test/java/PKNU/first_spring/service/MemberServiceTest.java @@ -0,0 +1,42 @@ +/* +package PKNU.first_spring.service; + +import PKNU.first_spring.domain.Member; +import PKNU.first_spring.repository.MemoryMemberRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class MemberServiceTest { + MemberService memberService; + MemoryMemberRepository memberRepository; + + @BeforeEach + public void setUp() { + memberRepository = new MemoryMemberRepository(); + memberService = new MemberService(memberRepository); + } + @Test + public void 회원삭제(){ + //Arrange + Member member1 = new Member(); + member1.setName("Spring1"); + Member member2 = new Member(); + member2.setName("Spring2"); + + memberService.join(member1); + memberService.join(member2); + + List result = memberRepository.findAll(); + + //Act + memberService.delete("Spring1"); + memberService.findMembers(); + + //Assert + List result1 = memberRepository.findAll(); + System.out.println("result = " + result1); + } +} +*/ diff --git a/src/test/java/PKNU/first_spring/service/QuizServiceTest.java b/src/test/java/PKNU/first_spring/service/QuizServiceTest.java new file mode 100644 index 0000000..6bef3db --- /dev/null +++ b/src/test/java/PKNU/first_spring/service/QuizServiceTest.java @@ -0,0 +1,15 @@ +/* +package PKNU.first_spring.service; + +import org.junit.jupiter.api.Test; + +public class QuizServiceTest { + QuizService quizService = new QuizService(); + + @Test + public void isCollect(){ + String answer = "한화이글스"; + System.out.println(quizService.isCorrect(answer)); + } +} +*/