├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── com │ │ └── example │ │ └── kotlinentitytutorial │ │ ├── Application.kt │ │ ├── Board.kt │ │ ├── BoardRepository.kt │ │ ├── BoardService.kt │ │ ├── Controller.kt │ │ ├── PrimaryKeyEntity.kt │ │ ├── Tag.kt │ │ ├── TagRepository.kt │ │ ├── User.kt │ │ ├── UserRepository.kt │ │ └── UserService.kt └── resources │ └── application.yml └── test └── kotlin └── com └── example └── kotlinentitytutorial └── ApplicationTests.kt /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin JPA Entity Tutorial 2 | 3 | Kotlin으로 JPA Entity를 보다 Entity 스럽게 사용해보기 위한 소개자료로 사용하는 튜토리얼용 프로젝트 입니다. 4 | 5 | ## 유저 스토리 6 | 7 | - 사용자는 게시판의 유형과 제목, 내용, 기타정보, 작성자 입력하여 게시판을 생성할 수 있습니다. 8 | - 사용자는 생성된 게시판의 상세조회를 통해 게시판의 유형, 제목, 내용, 기타정보, 작성자를 조회할 수 있습니다. 9 | - 사용자는 생성된 게시판의 제목과 내용, 기타정보를 수정할 수 있습니다. 10 | - 사용자는 생성된 게시판에 태그를 추가할 수 있습니다. 11 | - 사용자는 생성된 게시판에 이미 존재하는 태그를 삭제할 수 있습니다. 12 | - 사용자는 생성된 게시판에 댓글을 추가할 수 있습니다. 13 | - 사용자는 자신의 게시글을 조회할 수 있습니다. 14 | - 사용자가 삭제되면 사용자가 작성한 게시글이 모두 삭제됩니다. 15 | 16 | ## 블로그 링크 17 | 18 | [Kotlin JPA Entity에 대한 고찰](https://veluxer62.github.io/explanation/kotlin-jpa-entity/) 19 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.7.2" 5 | id("io.spring.dependency-management") version "1.0.12.RELEASE" 6 | kotlin("jvm") version "1.7.0" 7 | kotlin("plugin.spring") version "1.7.0" 8 | kotlin("plugin.jpa") version "1.7.0" 9 | } 10 | 11 | group = "com.example" 12 | version = "0.0.1-SNAPSHOT" 13 | java.sourceCompatibility = JavaVersion.VERSION_17 14 | 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | implementation("org.springframework.boot:spring-boot-starter-data-jpa") 21 | implementation("org.springframework.boot:spring-boot-starter-web") 22 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 23 | implementation("org.jetbrains.kotlin:kotlin-reflect") 24 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 25 | implementation("com.github.f4b6a3:ulid-creator:5.0.0") 26 | runtimeOnly("com.h2database:h2") 27 | testImplementation("org.springframework.boot:spring-boot-starter-test") 28 | } 29 | 30 | tasks.withType { 31 | kotlinOptions { 32 | freeCompilerArgs = listOf("-Xjsr305=strict") 33 | jvmTarget = "17" 34 | } 35 | } 36 | 37 | tasks.withType { 38 | useJUnitPlatform() 39 | } 40 | 41 | allOpen { 42 | annotation("javax.persistence.Entity") 43 | annotation("javax.persistence.MappedSuperclass") 44 | annotation("javax.persistence.Embeddable") 45 | } 46 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/veluxer62/kotlin-entity-tutorial/87a88fc143c91d011a232ce920a62b513be68e58/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "kotlin-entity-tutorial" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/Application.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class Application 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/Board.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import java.time.LocalDateTime 4 | import java.util.UUID 5 | import javax.persistence.CascadeType 6 | import javax.persistence.CollectionTable 7 | import javax.persistence.Column 8 | import javax.persistence.ElementCollection 9 | import javax.persistence.Embeddable 10 | import javax.persistence.Embedded 11 | import javax.persistence.Entity 12 | import javax.persistence.FetchType 13 | import javax.persistence.JoinColumn 14 | import javax.persistence.JoinTable 15 | import javax.persistence.ManyToMany 16 | import javax.persistence.ManyToOne 17 | 18 | @Entity 19 | class Board( 20 | title: String, 21 | content: String, 22 | information: BoardInformation, 23 | writer: User, 24 | tags: Set, 25 | ) : PrimaryKeyEntity() { 26 | @Column(nullable = false) 27 | var createdAt: LocalDateTime = LocalDateTime.now() 28 | protected set 29 | 30 | @Column(nullable = false) 31 | var title: String = title 32 | protected set 33 | 34 | @Column(nullable = false, length = 3000) 35 | var content: String = content 36 | protected set 37 | 38 | @Embedded 39 | var information: BoardInformation = information 40 | protected set 41 | 42 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 43 | @JoinColumn(nullable = false) 44 | var writer: User = writer 45 | protected set 46 | 47 | @ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.PERSIST, CascadeType.MERGE]) 48 | @JoinTable( 49 | name = "board_tag_assoc", 50 | joinColumns = [JoinColumn(name = "board_id")], 51 | inverseJoinColumns = [JoinColumn(name = "tag_id")], 52 | ) 53 | protected val mutableTags: MutableSet = tags.toMutableSet() 54 | val tags: Set get() = mutableTags.toSet() 55 | 56 | @ElementCollection 57 | @CollectionTable(name = "board_comment") 58 | private val mutableComments: MutableList = mutableListOf() 59 | val comments: List get() = mutableComments.toList() 60 | 61 | fun update(data: BoardUpdateData) { 62 | title = data.title 63 | content = data.content 64 | information = data.information 65 | } 66 | 67 | fun addTag(tag: Tag) { 68 | mutableTags.add(tag) 69 | } 70 | 71 | fun removeTag(tagId: UUID) { 72 | mutableTags.removeIf { it.id == tagId } 73 | } 74 | 75 | fun addComment(comment: Comment) { 76 | mutableComments.add(comment) 77 | } 78 | 79 | init { 80 | writer.writeBoard(this) 81 | } 82 | } 83 | 84 | @Embeddable 85 | data class BoardInformation( 86 | @Column(name = "link") 87 | private var _link: String?, 88 | 89 | @Column(name = "rank", nullable = false) 90 | private var _rank: Int, 91 | ) { 92 | val link: String? get() = _link 93 | val rank: Int get() = _rank 94 | } 95 | 96 | @Embeddable 97 | data class Comment( 98 | @Column(name = "content", length = 3000) 99 | private var _content: String, 100 | 101 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 102 | @JoinColumn(name = "writer_id") 103 | private var _writer: User, 104 | ) { 105 | val content: String get() = _content 106 | val writer: User get() = _writer 107 | } 108 | 109 | data class BoardUpdateData( 110 | val title: String, 111 | val content: String, 112 | val information: BoardInformation, 113 | ) 114 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/BoardRepository.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository 4 | import java.util.UUID 5 | 6 | interface BoardRepository : JpaRepository 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/BoardService.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import org.springframework.stereotype.Service 4 | import org.springframework.transaction.annotation.Transactional 5 | import java.util.UUID 6 | 7 | @Service 8 | @Transactional(readOnly = true) 9 | class BoardService( 10 | private val userRepository: UserRepository, 11 | private val boardRepository: BoardRepository, 12 | private val tagRepository: TagRepository, 13 | ) { 14 | @Transactional 15 | fun create(command: BoardCreationCommand): Board { 16 | val user = getUserById(command.writerId) 17 | val tags = command.tags.map { findOrCreateTag(it) }.toSet() 18 | 19 | return boardRepository.save(command.toEntity(user, tags)) 20 | } 21 | 22 | @Transactional 23 | fun update(id: UUID, command: BoardUpdateCommand): Board { 24 | return getById(id).apply { update(command.toData()) } 25 | } 26 | 27 | @Transactional 28 | fun addTag(id: UUID, command: TagCreationCommand,): Board { 29 | return getById(id).apply { addTag(findOrCreateTag(command)) } 30 | } 31 | 32 | @Transactional 33 | fun removeTag(id: UUID, tagId: UUID): Board { 34 | return getById(id).apply { removeTag(tagId) } 35 | } 36 | 37 | @Transactional 38 | fun addComment(id: UUID, command: CommentCreationCommand): Board { 39 | return getById(id) 40 | .apply { 41 | val user = getUserById(command.writerId) 42 | val comment = Comment(command.content, user) 43 | addComment(comment) 44 | } 45 | } 46 | 47 | fun getById(id: UUID): Board = boardRepository.findById(id).orElseThrow() 48 | 49 | private fun getUserById(writerId: UUID): User = userRepository.findById(writerId).orElseThrow() 50 | 51 | private fun findOrCreateTag(command: TagCreationCommand): Tag = 52 | tagRepository.findByKeyAndValue(command.key, command.value).orElse(command.toEntity()) 53 | } 54 | 55 | data class CommentCreationCommand( 56 | val content: String, 57 | val writerId: UUID, 58 | ) 59 | 60 | data class BoardUpdateCommand( 61 | val title: String, 62 | val content: String, 63 | val information: BoardInformationCommand, 64 | ) { 65 | fun toData() = BoardUpdateData( 66 | title = title, 67 | content = content, 68 | information = information.toEntity(), 69 | ) 70 | } 71 | 72 | data class BoardCreationCommand( 73 | val title: String, 74 | val content: String, 75 | val information: BoardInformationCommand, 76 | val writerId: UUID, 77 | val tags: Set, 78 | ) { 79 | fun toEntity(writer: User, tags: Set) = Board( 80 | title = title, 81 | content = content, 82 | information = information.toEntity(), 83 | writer = writer, 84 | tags = tags, 85 | ) 86 | } 87 | 88 | data class BoardInformationCommand( 89 | val link: String?, 90 | val rank: Int, 91 | ) { 92 | fun toEntity() = BoardInformation(link, rank) 93 | } 94 | 95 | data class TagCreationCommand( 96 | val key: String, 97 | val value: String, 98 | ) { 99 | fun toEntity() = Tag(key, value) 100 | } 101 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/Controller.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import java.time.LocalDateTime 4 | import org.springframework.web.bind.annotation.DeleteMapping 5 | import org.springframework.web.bind.annotation.GetMapping 6 | import org.springframework.web.bind.annotation.PathVariable 7 | import org.springframework.web.bind.annotation.PostMapping 8 | import org.springframework.web.bind.annotation.PutMapping 9 | import org.springframework.web.bind.annotation.RequestBody 10 | import org.springframework.web.bind.annotation.RestController 11 | import java.util.UUID 12 | 13 | @RestController 14 | class Controller( 15 | private val userService: UserService, 16 | private val boardService: BoardService, 17 | ) { 18 | @PostMapping("/users") 19 | fun createUser(@RequestBody command: UserCreationCommand): UserDto = 20 | UserDto(userService.create(command)) 21 | 22 | @DeleteMapping("/users/{id}") 23 | fun deleteUser(@PathVariable id: UUID) = userService.delete(id) 24 | 25 | @PostMapping("/boards") 26 | fun createBoard(@RequestBody command: BoardCreationCommand): BoardDto = 27 | BoardDto(boardService.create(command)) 28 | 29 | @PutMapping("/boards/{id}") 30 | fun updateBoard(@PathVariable id: UUID, @RequestBody command: BoardUpdateCommand): BoardDto = 31 | BoardDto(boardService.update(id, command)) 32 | 33 | @PostMapping("/boards/{id}/tags") 34 | fun addTag(@PathVariable id: UUID, @RequestBody command: TagCreationCommand): BoardDto = 35 | BoardDto(boardService.addTag(id, command)) 36 | 37 | @DeleteMapping("/boards/{id}/tags/{tagId}") 38 | fun removeTag(@PathVariable id: UUID, @PathVariable tagId: UUID): BoardDto = 39 | BoardDto(boardService.removeTag(id, tagId)) 40 | 41 | @PostMapping("/boards/{id}/comments") 42 | fun addComment(@PathVariable id: UUID, @RequestBody command: CommentCreationCommand): BoardDto = 43 | BoardDto(boardService.addComment(id, command)) 44 | 45 | @GetMapping("/boards/{id}") 46 | fun getBoard(@PathVariable id: UUID): BoardDto = BoardDto(boardService.getById(id)) 47 | } 48 | 49 | data class UserDto( 50 | val id: UUID, 51 | val name: String, 52 | ) { 53 | constructor(entity: User) : this(entity.id, entity.name) 54 | } 55 | 56 | data class BoardInformationDto( 57 | val link: String?, 58 | val rank: Int, 59 | ) { 60 | constructor(entity: BoardInformation) : this(entity.link, entity.rank) 61 | } 62 | 63 | data class TagDto( 64 | val id: UUID, 65 | val key: String, 66 | val value: String, 67 | ) { 68 | constructor(entity: Tag) : this(entity.id, entity.key, entity.value) 69 | } 70 | 71 | data class CommentDto( 72 | val content: String, 73 | val writer: UserDto, 74 | ) { 75 | constructor(entity: Comment) : this(entity.content, UserDto(entity.writer)) 76 | } 77 | 78 | data class BoardDto( 79 | val id: UUID, 80 | val createdAt: LocalDateTime, 81 | val title: String, 82 | val content: String, 83 | val information: BoardInformationDto, 84 | val writer: UserDto, 85 | val tags: Set, 86 | val comments: List, 87 | ) { 88 | constructor(entity: Board) : this( 89 | id = entity.id, 90 | createdAt = entity.createdAt, 91 | title = entity.title, 92 | content = entity.content, 93 | information = BoardInformationDto(entity.information), 94 | writer = UserDto(entity.writer), 95 | tags = entity.tags.map { TagDto(it) }.toSet(), 96 | comments = entity.comments.map { CommentDto(it) }, 97 | ) 98 | } 99 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/PrimaryKeyEntity.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import com.github.f4b6a3.ulid.UlidCreator 4 | import org.hibernate.proxy.HibernateProxy 5 | import org.springframework.data.domain.Persistable 6 | import java.io.Serializable 7 | import java.util.* 8 | import javax.persistence.Column 9 | import javax.persistence.Id 10 | import javax.persistence.MappedSuperclass 11 | import javax.persistence.PostLoad 12 | import javax.persistence.PostPersist 13 | 14 | @MappedSuperclass 15 | abstract class PrimaryKeyEntity : Persistable { 16 | @Id 17 | @Column(columnDefinition = "uuid") 18 | private val id: UUID = UlidCreator.getMonotonicUlid().toUuid() 19 | 20 | @Transient 21 | private var _isNew = true 22 | 23 | override fun getId(): UUID = id 24 | 25 | override fun isNew(): Boolean = _isNew 26 | 27 | override fun equals(other: Any?): Boolean { 28 | if (other == null) { 29 | return false 30 | } 31 | 32 | if (other !is HibernateProxy && this::class != other::class) { 33 | return false 34 | } 35 | 36 | return id == getIdentifier(other) 37 | } 38 | 39 | private fun getIdentifier(obj: Any): Serializable { 40 | return if (obj is HibernateProxy) { 41 | obj.hibernateLazyInitializer.identifier 42 | } else { 43 | (obj as PrimaryKeyEntity).id 44 | } 45 | } 46 | 47 | override fun hashCode() = Objects.hashCode(id) 48 | 49 | @PostPersist 50 | @PostLoad 51 | protected fun load() { 52 | _isNew = false 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/Tag.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import javax.persistence.Column 4 | import javax.persistence.Entity 5 | import javax.persistence.Table 6 | import javax.persistence.UniqueConstraint 7 | 8 | @Entity 9 | @Table(uniqueConstraints = [UniqueConstraint(name = "tag_key_value_uk", columnNames = ["`key`", "`value`"])]) 10 | class Tag( 11 | key: String, 12 | value: String, 13 | ) : PrimaryKeyEntity() { 14 | @Column(name = "`key`", nullable = false) 15 | var key: String = key 16 | protected set 17 | 18 | @Column(name = "`value`", nullable = false) 19 | var value: String = value 20 | protected set 21 | } 22 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/TagRepository.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository 4 | import java.util.Optional 5 | import java.util.UUID 6 | 7 | interface TagRepository : JpaRepository { 8 | fun findByKeyAndValue(key: String, value: String): Optional 9 | } 10 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/User.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import javax.persistence.CascadeType 4 | import javax.persistence.Column 5 | import javax.persistence.Entity 6 | import javax.persistence.FetchType 7 | import javax.persistence.OneToMany 8 | import javax.persistence.Table 9 | 10 | @Entity 11 | @Table(name = "`user`") 12 | class User( 13 | name: String, 14 | ) : PrimaryKeyEntity() { 15 | @Column(nullable = false, unique = true) 16 | var name: String = name 17 | protected set 18 | 19 | @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.ALL], mappedBy = "writer") 20 | protected val mutableBoards: MutableList = mutableListOf() 21 | val boards: List get() = mutableBoards.toList() 22 | 23 | fun writeBoard(board: Board) { 24 | mutableBoards.add(board) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/UserRepository.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository 4 | import java.util.UUID 5 | 6 | interface UserRepository : JpaRepository 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/kotlinentitytutorial/UserService.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import org.springframework.stereotype.Service 4 | import org.springframework.transaction.annotation.Transactional 5 | import java.util.UUID 6 | 7 | @Service 8 | class UserService( 9 | private val userRepository: UserRepository, 10 | ) { 11 | @Transactional 12 | fun create(command: UserCreationCommand): User { 13 | return userRepository.save(command.toEntity()) 14 | } 15 | 16 | @Transactional 17 | fun delete(id: UUID) { 18 | userRepository.deleteById(id) 19 | } 20 | } 21 | 22 | data class UserCreationCommand( 23 | val name: String, 24 | ) { 25 | fun toEntity() = User(name) 26 | } 27 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | jpa: 3 | show-sql: true 4 | properties: 5 | hibernate: 6 | format_sql: true 7 | -------------------------------------------------------------------------------- /src/test/kotlin/com/example/kotlinentitytutorial/ApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.example.kotlinentitytutorial 2 | 3 | import java.util.UUID 4 | import org.junit.jupiter.api.Assertions.assertAll 5 | import org.junit.jupiter.api.Assertions.assertEquals 6 | import org.junit.jupiter.api.Test 7 | import org.springframework.boot.test.context.SpringBootTest 8 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT 9 | import org.springframework.boot.test.web.server.LocalServerPort 10 | import org.springframework.boot.web.client.RestTemplateBuilder 11 | import org.springframework.http.HttpEntity 12 | import org.springframework.http.HttpMethod 13 | import org.springframework.http.HttpStatus 14 | import org.springframework.http.ResponseEntity 15 | import org.springframework.web.client.RestTemplate 16 | 17 | @SpringBootTest(webEnvironment = RANDOM_PORT) 18 | class ApplicationTests( 19 | @LocalServerPort private val port: Int, 20 | ) { 21 | private val restTemplate: RestTemplate = RestTemplateBuilder().rootUri("http://localhost:$port").build() 22 | 23 | @Test 24 | fun test_create_user() { 25 | // Given 26 | val request = UserCreationCommand("홍길동") 27 | 28 | // When 29 | val actual = restTemplate.postForEntity("/users", request, UserDto::class.java) 30 | 31 | // Then 32 | assertEquals(HttpStatus.OK, actual.statusCode) 33 | assertEquals("홍길동", actual.body?.name) 34 | } 35 | 36 | @Test 37 | fun test_create_board() { 38 | // Given 39 | val user = createUser() 40 | val request = BoardCreationCommand( 41 | title = "게시판", 42 | content = "내용", 43 | information = BoardInformationCommand(null, 1), 44 | writerId = user.id, 45 | tags = setOf( 46 | TagCreationCommand("카테고리", "자유게시판"), 47 | TagCreationCommand("분류", "IT") 48 | ), 49 | ) 50 | 51 | // When 52 | val actual = restTemplate.postForEntity("/boards", request, BoardDto::class.java) 53 | 54 | // Then 55 | assertEquals(HttpStatus.OK, actual.statusCode) 56 | 57 | val actualBody = actual.body!! 58 | assertAll( 59 | { assertEquals("게시판", actualBody.title) }, 60 | { assertEquals("내용", actualBody.content) }, 61 | { assertEquals(BoardInformationDto(null, 1), actualBody.information) }, 62 | { assertEquals(user, actualBody.writer) }, 63 | { assertEquals(2, actualBody.tags.size) }, 64 | ) 65 | } 66 | 67 | @Test 68 | fun test_update_board() { 69 | // Given 70 | val board = createBoard(createUser()) 71 | val request = BoardUpdateCommand( 72 | title = "제목 수정", 73 | content = "내용 수정", 74 | information = BoardInformationCommand("https://google.com", 2), 75 | ) 76 | 77 | // When 78 | val actual = restTemplate.putForEntity("/boards/${board.id}", request, BoardDto::class.java) 79 | 80 | // Then 81 | assertEquals(HttpStatus.OK, actual.statusCode) 82 | 83 | val actualBody = actual.body!! 84 | assertAll( 85 | { assertEquals("제목 수정", actualBody.title) }, 86 | { assertEquals("내용 수정", actualBody.content) }, 87 | { assertEquals(BoardInformationDto("https://google.com", 2), actualBody.information) }, 88 | ) 89 | } 90 | 91 | @Test 92 | fun test_add_tag() { 93 | // Given 94 | val board = createBoard(createUser()) 95 | val request = TagCreationCommand( 96 | key = "색상", 97 | value = "빨강", 98 | ) 99 | 100 | // When 101 | val actual = restTemplate.postForEntity("/boards/${board.id}/tags", request, BoardDto::class.java) 102 | 103 | // Then 104 | assertEquals(HttpStatus.OK, actual.statusCode) 105 | assertEquals(3, actual.body?.tags?.size) 106 | } 107 | 108 | @Test 109 | fun test_remove_tag() { 110 | // Given 111 | val board = createBoard(createUser()) 112 | val removeTagId = board.tags.first().id 113 | 114 | // When 115 | val actual = restTemplate.deleteForEntity("/boards/${board.id}/tags/$removeTagId", BoardDto::class.java) 116 | 117 | // Then 118 | assertEquals(HttpStatus.OK, actual.statusCode) 119 | assertEquals(1, actual.body?.tags?.size) 120 | } 121 | 122 | @Test 123 | fun test_add_comment() { 124 | // Given 125 | val board = createBoard(createUser()) 126 | val user = createUser() 127 | val request = CommentCreationCommand( 128 | content = "코멘트", 129 | writerId = user.id, 130 | ) 131 | 132 | // When 133 | val actual = restTemplate.postForEntity("/boards/${board.id}/comments", request, BoardDto::class.java) 134 | 135 | // Then 136 | assertEquals(HttpStatus.OK, actual.statusCode) 137 | 138 | val actualBody = actual.body!!.comments.last() 139 | assertAll( 140 | { assertEquals("코멘트", actualBody.content) }, 141 | { assertEquals(user, actualBody.writer) }, 142 | ) 143 | } 144 | 145 | @Test 146 | fun test_get_board() { 147 | // Given 148 | val user = createUser() 149 | val board = createBoard(user) 150 | addComment(board) 151 | 152 | // When 153 | val actual = restTemplate.getForEntity("/boards/${board.id}", BoardDto::class.java) 154 | 155 | // Then 156 | assertEquals(HttpStatus.OK, actual.statusCode) 157 | 158 | val actualBody = actual.body!! 159 | assertAll( 160 | { assertEquals("게시판", actualBody.title) }, 161 | { assertEquals("내용", actualBody.content) }, 162 | { assertEquals(BoardInformationDto(null, 1), actualBody.information) }, 163 | { assertEquals(user, actualBody.writer) }, 164 | { assertEquals(2, actualBody.tags.size) }, 165 | { assertEquals(1, actualBody.comments.size) }, 166 | ) 167 | } 168 | 169 | @Test 170 | fun test_delete_user() { 171 | // Given 172 | val user = createUser() 173 | addComment(createBoard(user)) 174 | 175 | // When 176 | val actual = restTemplate.deleteForEntity("/users/${user.id}", Unit::class.java) 177 | 178 | // Then 179 | assertEquals(HttpStatus.OK, actual.statusCode) 180 | } 181 | 182 | private fun createUser(): UserDto = 183 | restTemplate.postForEntity("/users", UserCreationCommand(UUID.randomUUID().toString()), UserDto::class.java).body!! 184 | 185 | private fun createBoard(user: UserDto): BoardDto { 186 | val request = BoardCreationCommand( 187 | title = "게시판", 188 | content = "내용", 189 | information = BoardInformationCommand(null, 1), 190 | writerId = user.id, 191 | tags = setOf( 192 | TagCreationCommand("카테고리", "자유게시판"), 193 | TagCreationCommand("분류", "IT") 194 | ), 195 | ) 196 | 197 | return restTemplate.postForEntity("/boards", request, BoardDto::class.java).body!! 198 | } 199 | 200 | private fun addComment(board: BoardDto): BoardDto { 201 | val request = CommentCreationCommand( 202 | content = "코멘트", 203 | writerId = board.writer.id, 204 | ) 205 | 206 | return restTemplate.postForEntity("/boards/${board.id}/comments", request, BoardDto::class.java).body!! 207 | } 208 | } 209 | 210 | fun RestTemplate.putForEntity(url: String, request: Any, responseType: Class): ResponseEntity { 211 | return this.exchange(url, HttpMethod.PUT, HttpEntity(request), responseType) 212 | } 213 | 214 | fun RestTemplate.deleteForEntity(url: String, responseType: Class): ResponseEntity { 215 | return this.exchange(url, HttpMethod.DELETE, HttpEntity.EMPTY, responseType) 216 | } 217 | --------------------------------------------------------------------------------