diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..bdce78c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,83 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ +application.yml + +### 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/ + +*# +*.iml +*.ipr +*.iws +*.jar +*.sw? +*~ +.#* +.*.md.html +.DS_Store +.attach_pid* +.classpath +.factorypath +.gradle +.metadata +.project +.recommenders +.settings +.springBeans +.vscode +/code +MANIFEST.MF +_site/ +activemq-data +bin +build +!/**/src/**/bin +!/**/src/**/build +build.log +dependency-reduced-pom.xml +dump.rdb +interpolated*.xml +lib/ +manifest.yml +out +overridedb.* +target +.flattened-pom.xml +secrets.yml +.gradletasknamecache +.sts4-cache + +.idea +.env diff --git a/README.md b/README.md index a394e048..787950b5 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,151 @@ -# spring-instagram-20th -CEOS 20th BE study - instagram clone coding +## 1. 데이터베이스 모델링 + +## pre. 요구사항 분석 + +**[인스타그램 서비스 분석]** + +### 1. 서비스 개요 + +인스타그램은 사용자들이 게시글을 작성하고, 댓글을 달며, 좋아요를 누르고, 메시지를 주고받을 수 있는 기능을 제공합니다. + +### 2. 기능 요구사항 + +### 2.1 게시글 기능 + +- **게시글 조회**: 사용자는 타인의 게시글을 조회할 수 있습니다. +- **게시글 작성**: 사용자는 텍스트와 사진을 포함하여 게시글을 작성할 수 있습니다. +- **게시글 수정 및 삭제**: 사용자는 자신이 작성한 게시글을 수정하거나 삭제할 수 있습니다. + +### 2.2 댓글 기능 + +- **댓글 작성**: 사용자는 게시글에 댓글을 작성할 수 있습니다. +- **대댓글 기능**: 사용자는 댓글에 대한 대댓글을 작성할 수 있습니다. +- **댓글 수정 및 삭제**: 사용자는 자신이 작성한 댓글 및 대댓글을 수정하거나 삭제할 수 있습니다. + +### 2.3 좋아요 기능 + +- **좋아요**: 사용자는 게시글에 좋아요를 누를 수 있습니다. +- **좋아요 취소**: 사용자는 자신이 누른 좋아요를 취소할 수 있습니다. + +### 2.4 Direct Message (DM) 기능 + +- **DM 작성**: 사용자는 다른 사용자와 1:1로 메시지를 주고받을 수 있습니다. +- **DM 삭제**: 사용자는 자신이 보낸 DM을 삭제할 수 있습니다. + +### 구현 계획 + +### Domain (Entity) 클래스 + +- 각 테이블에 대응하는 Entity 클래스를 정의하고, JPA 어노테이션을 통해 MySQL 데이터베이스와 매핑합니다. + +### Repository 계층 + +- **JpaRepository**를 확장한 Repository 인터페이스를 정의하여, 기본 CRUD 작업을 자동으로 수행합니다. + +### 서비스 계층 + +- 비즈니스 로직을 처리하며, Repository를 통해 데이터베이스와 상호작용합니다. + +### 컨트롤러 계층 + +- 사용자 요청을 처리하고, 클라이언트와 서버 간의 데이터 교환을 관리합니다. + +## 1) 개념적 설계 + +**1-1) 개체(entity)와 속성(attribute) 추출** + +**1. 사용자 (Users)** + +- **UserID** (PK) : 사용자 고유 식별자 +- **Username** : 사용자 이름 +- **Email** : 이메일 주소 +- **Password** : 암호 +- **ProfilePicture** : 프로필 사진 +- **Bio** : 사용자 소개 + +**2. 게시글 (Post)** + +- **PostID** (PK) : 게시글 고유 식별자 +- **UserID** (FK) : 게시글 작성자 +- **Image** : 이미지 파일 +- **Caption** : 게시글 내용 +- **Timestamp** : 작성 시간 + +**3. 댓글 (Comment)** + +- **CommentID** (PK) : 댓글 고유 식별자 +- **PostID** (FK) : 댓글이 달린 게시글 +- **UserID** (FK) : 댓글 작성자 +- **Text** : 댓글 내용 +- **Timestamp** : 댓글 작성 시간 + +**4. 대댓글 (Reply)** + +- **ReplyID** (PK) : 대댓글 고유 식별자 +- **CommentID** (FK) : 대댓글이 달린 댓글 +- **UserID** (FK) : 대댓글 작성자 +- **Text** : 대댓글 내용 +- **Timestamp** : 대댓글 작성 시간 + +**5. 좋아요 (Likes)** + +- **LikeID** (PK) : 좋아요 고유 식별자 +- **PostID** (FK) : 좋아요가 달린 게시글 +- **UserID** (FK) : 좋아요를 누른 사용자 +- **Timestamp** : 좋아요 시간 + +**6. 다이렉트 메시지 (DirectMessage)** + +- **MessageID** (PK) : 메시지 고유 식별자 +- **SenderID** (FK) : 메시지 발신자 +- **ReceiverID** (FK) : 메시지 수신자 +- **Text** : 메시지 내용 +- **Timestamp** : 메시지 전송 시간 + +## 2) 논리적 설계 + +릴레이션(스키마) + +개체 → 릴레이션 이름 + +속성 → 릴레이션의 속성 + +![erd](https://github.com/user-attachments/assets/49eea983-2974-45d1-aa0c-f19a31790f66) + +## 3) 물리적 설계 + +**SQL문 작성 예시** + +-- 사용자 테이블 +CREATE TABLE User ( +UserID INT PRIMARY KEY AUTO_INCREMENT, +Username VARCHAR(50) NOT NULL, +Email VARCHAR(100) NOT NULL UNIQUE, +Password VARCHAR(100) NOT NULL, +ProfilePicture VARCHAR(255), +); + +-- 게시글 테이블 +CREATE TABLE Post ( +PostID INT PRIMARY KEY AUTO_INCREMENT, +UserID INT, +Image VARCHAR(255), +Caption TEXT, +Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, +FOREIGN KEY (UserID) REFERENCES User(UserID) +); + + +테이블이름 user로 했더니 단위테스트에서 오류계속발생.. + +다른 분들은 잘되는것같길래 안바꾸고 해봤는데 계속 안돼서 users로 테이블 이름 변경하니 성공. . + + +![image (2)](https://github.com/user-attachments/assets/ace93beb-c781-4ab6-a3d2-c5a2ad068f8c) + +# REPOSITORY 단위테스트 + +- `given` : 테스트 실행을 준비하는 단계 +- `when` : 테스트를 진행하는 단계 +- `then` : 테스트 결과를 검증하는 단계 + diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..db38b6ae --- /dev/null +++ b/build.gradle @@ -0,0 +1,41 @@ +/*plugins { + id 'java' + id 'org.springframework.boot' version '3.3.3' + id 'io.spring.dependency-management' version '1.1.6' +}*/ +plugins { + id 'org.springframework.boot' version '3.1.2' // 스프링 부트 버전 + id 'io.spring.dependency-management' version '1.1.0' + id 'java' +} +group = 'com.ceos20' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.assertj:assertj-core:3.20.2' + + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + runtimeOnly 'com.h2database:h2' + runtimeOnly 'com.mysql:mysql-connector-j' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..a4413138 --- /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.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..b740cf13 --- /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/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 "${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 00000000..25da30db --- /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 00000000..19b52044 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'spring-boot' diff --git a/src/main/java/com/ceos20/springinstagram/SpringInstagramApplication.java b/src/main/java/com/ceos20/springinstagram/SpringInstagramApplication.java new file mode 100644 index 00000000..f5bee5b9 --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/SpringInstagramApplication.java @@ -0,0 +1,12 @@ +package com.ceos20.springinstagram; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringInstagramApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringInstagramApplication.class, args); + } +} diff --git a/src/main/java/com/ceos20/springinstagram/domain/Comment.java b/src/main/java/com/ceos20/springinstagram/domain/Comment.java new file mode 100644 index 00000000..3ae69016 --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/domain/Comment.java @@ -0,0 +1,25 @@ +package com.ceos20.springinstagram.domain; + +import jakarta.persistence.*; +import lombok.Data; +import java.time.LocalDateTime; + +@Entity +@Data +public class Comment { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long commentId; + + @ManyToOne + @JoinColumn(name = "postId") + private Post post; + + @ManyToOne + @JoinColumn(name = "userId") + private User user; + + private String text; + private LocalDateTime timestamp; +} + diff --git a/src/main/java/com/ceos20/springinstagram/domain/DirectMessage.java b/src/main/java/com/ceos20/springinstagram/domain/DirectMessage.java new file mode 100644 index 00000000..5b112b8c --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/domain/DirectMessage.java @@ -0,0 +1,30 @@ +package com.ceos20.springinstagram.domain; + +import jakarta.persistence.*; +import lombok.Data; +import java.time.LocalDateTime; + +@Entity +@Data +public class DirectMessage { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long messageId; + + @ManyToOne + @JoinColumn(name = "senderId") + private User sender; + + @ManyToOne + @JoinColumn(name = "receiverId") + private User receiver; + + private String text; + private LocalDateTime timestamp; + + /*@PrePersist + protected void onCreate() { + timestamp = LocalDateTime.now(); + } + */ +} diff --git a/src/main/java/com/ceos20/springinstagram/domain/Likes.java b/src/main/java/com/ceos20/springinstagram/domain/Likes.java new file mode 100644 index 00000000..7eb57486 --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/domain/Likes.java @@ -0,0 +1,23 @@ +package com.ceos20.springinstagram.domain; + +import jakarta.persistence.*; +import lombok.Data; +import java.time.LocalDateTime; + +@Entity +@Data +public class Likes { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long likeId; + + @ManyToOne + @JoinColumn(name = "postId") + private Post post; + + @ManyToOne + @JoinColumn(name = "userId") + private User user; + + private LocalDateTime timestamp; +} diff --git a/src/main/java/com/ceos20/springinstagram/domain/Post.java b/src/main/java/com/ceos20/springinstagram/domain/Post.java new file mode 100644 index 00000000..9a74e1b6 --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/domain/Post.java @@ -0,0 +1,22 @@ +package com.ceos20.springinstagram.domain; + +import jakarta.persistence.*; +import lombok.Data; +import java.time.LocalDateTime; + +@Entity +@Data +@Table(name = "post") +public class Post { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long postId; + + @ManyToOne + @JoinColumn(name = "userId") + private User user; + private String image; + private String caption; + private LocalDateTime timestamp; +} + diff --git a/src/main/java/com/ceos20/springinstagram/domain/Reply.java b/src/main/java/com/ceos20/springinstagram/domain/Reply.java new file mode 100644 index 00000000..2b332ddc --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/domain/Reply.java @@ -0,0 +1,24 @@ +package com.ceos20.springinstagram.domain; + +import jakarta.persistence.*; +import lombok.Data; +import java.time.LocalDateTime; + +@Entity +@Data +public class Reply { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long replyId; + + @ManyToOne + @JoinColumn(name = "commentId") + private Comment comment; + + @ManyToOne + @JoinColumn(name = "userId") + private User user; + + private String text; + private LocalDateTime timestamp; +} diff --git a/src/main/java/com/ceos20/springinstagram/domain/User.java b/src/main/java/com/ceos20/springinstagram/domain/User.java new file mode 100644 index 00000000..fe3dc835 --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/domain/User.java @@ -0,0 +1,21 @@ +package com.ceos20.springinstagram.domain; + +import jakarta.persistence.*; +import lombok.Data; + +@Entity +@Data +@Table(name = "users") +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long userId; + @Column(nullable = false) + private String username; + @Column(nullable = false) + private String email; + @Column(nullable = false) + private String password; + private String profilePicture; +} + diff --git a/src/main/java/com/ceos20/springinstagram/repository/CommentRepository.java b/src/main/java/com/ceos20/springinstagram/repository/CommentRepository.java new file mode 100644 index 00000000..9a56220c --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/repository/CommentRepository.java @@ -0,0 +1,10 @@ +package com.ceos20.springinstagram.repository; +import com.ceos20.springinstagram.domain.Post; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import com.ceos20.springinstagram.domain.Comment; +import java.util.List; + +@Repository +public interface CommentRepository extends JpaRepository { +} diff --git a/src/main/java/com/ceos20/springinstagram/repository/DirectMessageRepository.java b/src/main/java/com/ceos20/springinstagram/repository/DirectMessageRepository.java new file mode 100644 index 00000000..7408283a --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/repository/DirectMessageRepository.java @@ -0,0 +1,10 @@ +package com.ceos20.springinstagram.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import com.ceos20.springinstagram.domain.DirectMessage; + +@Repository +public interface DirectMessageRepository extends JpaRepository { +} + diff --git a/src/main/java/com/ceos20/springinstagram/repository/LikesRepository.java b/src/main/java/com/ceos20/springinstagram/repository/LikesRepository.java new file mode 100644 index 00000000..c19d16e3 --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/repository/LikesRepository.java @@ -0,0 +1,10 @@ +package com.ceos20.springinstagram.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import com.ceos20.springinstagram.domain.Likes; + +@Repository +public interface LikesRepository extends JpaRepository { +} + diff --git a/src/main/java/com/ceos20/springinstagram/repository/PostRepository.java b/src/main/java/com/ceos20/springinstagram/repository/PostRepository.java new file mode 100644 index 00000000..876e168f --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/repository/PostRepository.java @@ -0,0 +1,9 @@ +package com.ceos20.springinstagram.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import com.ceos20.springinstagram.domain.Post; + +@Repository +public interface PostRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/ceos20/springinstagram/repository/ReplyRepository.java b/src/main/java/com/ceos20/springinstagram/repository/ReplyRepository.java new file mode 100644 index 00000000..18eeb6aa --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/repository/ReplyRepository.java @@ -0,0 +1,9 @@ +package com.ceos20.springinstagram.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import com.ceos20.springinstagram.domain.Reply; + +@Repository +public interface ReplyRepository extends JpaRepository { +} diff --git a/src/main/java/com/ceos20/springinstagram/repository/UserRepository.java b/src/main/java/com/ceos20/springinstagram/repository/UserRepository.java new file mode 100644 index 00000000..5c3aa779 --- /dev/null +++ b/src/main/java/com/ceos20/springinstagram/repository/UserRepository.java @@ -0,0 +1,10 @@ +package com.ceos20.springinstagram.repository; + +import com.ceos20.springinstagram.domain.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + + +@Repository +public interface UserRepository extends JpaRepository { +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..9e7db663 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,18 @@ +spring: + datasource: + url: jdbc:mysql://localhost:3306/insta + username: root + password: 1234 + driver-class-name: com.mysql.cj.jdbc.Driver + + jpa: + hibernate: + ddl-auto: update + show-sql: true + properties: + hibernate: + format_sql: true + +logging: + level: + org.hibernate.SQL: debug \ No newline at end of file diff --git a/src/test/java/com/ceos20/springinstagram/SpringInstagramApplicationTests.java b/src/test/java/com/ceos20/springinstagram/SpringInstagramApplicationTests.java new file mode 100644 index 00000000..343e9762 --- /dev/null +++ b/src/test/java/com/ceos20/springinstagram/SpringInstagramApplicationTests.java @@ -0,0 +1,13 @@ +package com.ceos20.springinstagram; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringInstagramApplicationTests { + + @Test + void contextLoads() { + } + +} \ No newline at end of file diff --git a/src/test/java/com/ceos20/springinstagram/repository/PostRepositoryTest.java b/src/test/java/com/ceos20/springinstagram/repository/PostRepositoryTest.java new file mode 100644 index 00000000..19be1069 --- /dev/null +++ b/src/test/java/com/ceos20/springinstagram/repository/PostRepositoryTest.java @@ -0,0 +1,90 @@ +package com.ceos20.springinstagram.repository; + +import com.ceos20.springinstagram.domain.Post; +import com.ceos20.springinstagram.domain.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.jdbc.Sql; + +import jakarta.persistence.EntityManager; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@DataJpaTest +public class PostRepositoryTest { + + @Autowired + private PostRepository postRepository; + + @Autowired + private UserRepository userRepository; + + @Autowired + private EntityManager entityManager; // JPA 쿼리 확인을 위한 EntityManager + + @BeforeEach + public void setup() { + // Given - 3명의 유저를 저장 + User user1 = new User(); + user1.setUsername("user1"); + user1.setEmail("user1@test.com"); + user1.setPassword("password1"); + userRepository.save(user1); + + User user2 = new User(); + user2.setUsername("user2"); + user2.setEmail("user2@test.com"); + user2.setPassword("password2"); + userRepository.save(user2); + + User user3 = new User(); + user3.setUsername("user3"); + user3.setEmail("user3@test.com"); + user3.setPassword("password3"); + userRepository.save(user3); + + // Given - 3개의 포스트를 저장 + Post post1 = new Post(); + post1.setUser(user1); + post1.setImage("image1.jpg"); + post1.setCaption("caption1"); + post1.setTimestamp(LocalDateTime.now()); + postRepository.save(post1); + + Post post2 = new Post(); + post2.setUser(user2); + post2.setImage("image2.jpg"); + post2.setCaption("caption2"); + post2.setTimestamp(LocalDateTime.now()); + postRepository.save(post2); + + Post post3 = new Post(); + post3.setUser(user3); + post3.setImage("image3.jpg"); + post3.setCaption("caption3"); + post3.setTimestamp(LocalDateTime.now()); + postRepository.save(post3); + + // JPA 쿼리를 확인하기 위해 flush + entityManager.flush(); + entityManager.clear(); + } + + @Test + public void givenPosts_whenFindAll_thenReturnPosts() { + // When - 모든 포스트를 조회 + List posts = postRepository.findAll(); + + // Then - 조회된 포스트가 3개인지 확인 + assertThat(posts).hasSize(3); + + // Then - 각각의 포스트가 올바른지 확인 + assertThat(posts.get(0).getCaption()).isEqualTo("caption1"); + assertThat(posts.get(1).getCaption()).isEqualTo("caption2"); + assertThat(posts.get(2).getCaption()).isEqualTo("caption3"); + } +}