├── .gitignore ├── README.md ├── build.gradle ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── codingrecipe │ │ └── board │ │ ├── BoardApplication.java │ │ ├── config │ │ └── WebConfig.java │ │ ├── controller │ │ ├── BoardController.java │ │ ├── CommentController.java │ │ └── HomeController.java │ │ ├── dto │ │ ├── BoardDTO.java │ │ └── CommentDTO.java │ │ ├── entity │ │ ├── BaseEntity.java │ │ ├── BoardEntity.java │ │ ├── BoardFileEntity.java │ │ └── CommentEntity.java │ │ ├── repository │ │ ├── BoardFileRepository.java │ │ ├── BoardRepository.java │ │ └── CommentRepository.java │ │ └── service │ │ ├── BoardService.java │ │ └── CommentService.java └── resources │ ├── application.yml │ └── templates │ ├── detail.html │ ├── index.html │ ├── list.html │ ├── paging.html │ ├── save.html │ └── update.html └── test └── java └── com └── codingrecipe └── board └── BoardApplicationTests.java /.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 | # 개발환경 2 | 1. IDE: IntelliJ IDEA Community 3 | 2. Spring Boot 2.6.13 4 | 3. JDK 11 5 | 4. mysql 6 | 5. Spring Data JPA 7 | 6. Thymeleaf 8 | 9 | # 게시판 주요기능 10 | 1. 글쓰기(/board/save) 11 | 2. 글목록(/board/) 12 | 3. 글조회(/board/{id}) 13 | 4. 글수정(/board/update/{id}) 14 | - 상세화면에서 수정 버튼 클릭 15 | - 서버에서 해당 게시글의 정보를 가지고 수정 화면 출력 16 | - 제목, 내용 수정 입력 받아서 서버로 요청 17 | - 수정 처리 18 | 5. 글삭제(/board/delete/{id}) 19 | 6. 페이징처리(/board/paging) 20 | - /board/paging?page=2 21 | - /board/paging/2 22 | - 게시글 14 23 | - 한페이지에 5개씩 => 3개 24 | - 한페이지에 3개씩 => 5개 25 | 7. 파일(이미지)첨부하기 26 | - 단일 파일 첨부 27 | - 다중 파일 첨부 28 | - 파일 첨부와 관련하여 추가될 부분들 29 | - save.html 30 | - BoardDTO 31 | - BoardService.save() 32 | - BoardEntity 33 | - BoardFileEntity, BoardFileRepository 추가 34 | - detail.html 35 | - github에 올려놓은 코드를 보시고 어떤 부분이 바뀌는지 잘 살펴봐주세요. 36 | 37 | - board_table(부모) - board_file_table(자식) 38 | ``` 39 | create table board_table 40 | ( 41 | id bigint auto_increment primary key, 42 | created_time datetime null, 43 | updated_time datetime null, 44 | board_contents varchar(500) null, 45 | board_hits int null, 46 | board_pass varchar(255) null, 47 | board_title varchar(255) null, 48 | board_writer varchar(20) not null, 49 | file_attached int null 50 | ); 51 | 52 | create table board_file_table 53 | ( 54 | id bigint auto_increment primary key, 55 | created_time datetime null, 56 | updated_time datetime null, 57 | original_file_name varchar(255) null, 58 | stored_file_name varchar(255) null, 59 | board_id bigint null, 60 | constraint FKcfxqly70ddd02xbou0jxgh4o3 61 | foreign key (board_id) references board_table (id) on delete cascade 62 | ); 63 | ``` 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | ## mysql DataBase 계정 생성 및 권한 부여 75 | ``` 76 | create database db_codingrecipe; 77 | create user user_codingrecipe@localhost identified by '1234'; 78 | grant all privileges on db_codingrecipe.* to user_codingrecipe@localhost; 79 | ``` -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.6.13' 4 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 5 | } 6 | 7 | group = 'com.codingrecipe' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '11' 10 | 11 | configurations { 12 | compileOnly { 13 | extendsFrom annotationProcessor 14 | } 15 | } 16 | 17 | repositories { 18 | mavenCentral() 19 | } 20 | 21 | dependencies { 22 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 23 | implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' 24 | implementation 'org.springframework.boot:spring-boot-starter-web' 25 | compileOnly 'org.projectlombok:lombok' 26 | runtimeOnly 'mysql:mysql-connector-java' 27 | annotationProcessor 'org.projectlombok:lombok' 28 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 29 | } 30 | 31 | tasks.named('test') { 32 | useJUnitPlatform() 33 | } 34 | -------------------------------------------------------------------------------- /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: -------------------------------------------------------------------------------- 1 | rootProject.name = 'board' 2 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/BoardApplication.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class BoardApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(BoardApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | 7 | @Configuration 8 | public class WebConfig implements WebMvcConfigurer { 9 | private String resourcePath = "/upload/**"; // view 에서 접근할 경로 10 | private String savePath = "file:///C:/springboot_img/"; // 실제 파일 저장 경로(win) 11 | // private String savePath = "file:///Users/사용자이름/springboot_img/"; // 실제 파일 저장 경로(mac) 12 | 13 | @Override 14 | public void addResourceHandlers(ResourceHandlerRegistry registry) { 15 | registry.addResourceHandler(resourcePath) 16 | .addResourceLocations(savePath); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/controller/BoardController.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.controller; 2 | 3 | import com.codingrecipe.board.dto.BoardDTO; 4 | import com.codingrecipe.board.dto.CommentDTO; 5 | import com.codingrecipe.board.service.BoardService; 6 | import com.codingrecipe.board.service.CommentService; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.Pageable; 10 | import org.springframework.data.web.PageableDefault; 11 | import org.springframework.stereotype.Controller; 12 | import org.springframework.ui.Model; 13 | import org.springframework.web.bind.annotation.*; 14 | 15 | import java.io.IOException; 16 | import java.util.List; 17 | 18 | @Controller 19 | @RequiredArgsConstructor 20 | @RequestMapping("/board") 21 | public class BoardController { 22 | private final BoardService boardService; 23 | private final CommentService commentService; 24 | 25 | @GetMapping("/save") 26 | public String saveForm() { 27 | return "save"; 28 | } 29 | 30 | @PostMapping("/save") 31 | public String save(@ModelAttribute BoardDTO boardDTO) throws IOException { 32 | System.out.println("boardDTO = " + boardDTO); 33 | boardService.save(boardDTO); 34 | return "index"; 35 | } 36 | 37 | @GetMapping("/") 38 | public String findAll(Model model) { 39 | // DB에서 전체 게시글 데이터를 가져와서 list.html에 보여준다. 40 | List boardDTOList = boardService.findAll(); 41 | model.addAttribute("boardList", boardDTOList); 42 | return "list"; 43 | } 44 | 45 | @GetMapping("/{id}") 46 | public String findById(@PathVariable Long id, Model model, 47 | @PageableDefault(page=1) Pageable pageable) { 48 | /* 49 | 해당 게시글의 조회수를 하나 올리고 50 | 게시글 데이터를 가져와서 detail.html에 출력 51 | */ 52 | boardService.updateHits(id); 53 | BoardDTO boardDTO = boardService.findById(id); 54 | /* 댓글 목록 가져오기 */ 55 | List commentDTOList = commentService.findAll(id); 56 | model.addAttribute("commentList", commentDTOList); 57 | model.addAttribute("board", boardDTO); 58 | model.addAttribute("page", pageable.getPageNumber()); 59 | return "detail"; 60 | } 61 | 62 | @GetMapping("/update/{id}") 63 | public String updateForm(@PathVariable Long id, Model model) { 64 | BoardDTO boardDTO = boardService.findById(id); 65 | model.addAttribute("boardUpdate", boardDTO); 66 | return "update"; 67 | } 68 | 69 | @PostMapping("/update") 70 | public String update(@ModelAttribute BoardDTO boardDTO, Model model) { 71 | BoardDTO board = boardService.update(boardDTO); 72 | model.addAttribute("board", board); 73 | return "detail"; 74 | // return "redirect:/board/" + boardDTO.getId(); 75 | } 76 | 77 | @GetMapping("/delete/{id}") 78 | public String delete(@PathVariable Long id) { 79 | boardService.delete(id); 80 | return "redirect:/board/"; 81 | } 82 | 83 | // /board/paging?page=1 84 | @GetMapping("/paging") 85 | public String paging(@PageableDefault(page = 1) Pageable pageable, Model model) { 86 | // pageable.getPageNumber(); 87 | Page boardList = boardService.paging(pageable); 88 | int blockLimit = 3; 89 | int startPage = (((int)(Math.ceil((double)pageable.getPageNumber() / blockLimit))) - 1) * blockLimit + 1; // 1 4 7 10 ~~ 90 | int endPage = ((startPage + blockLimit - 1) < boardList.getTotalPages()) ? startPage + blockLimit - 1 : boardList.getTotalPages(); 91 | 92 | // page 갯수 20개 93 | // 현재 사용자가 3페이지 94 | // 1 2 3 95 | // 현재 사용자가 7페이지 96 | // 7 8 9 97 | // 보여지는 페이지 갯수 3개 98 | // 총 페이지 갯수 8개 99 | 100 | model.addAttribute("boardList", boardList); 101 | model.addAttribute("startPage", startPage); 102 | model.addAttribute("endPage", endPage); 103 | return "paging"; 104 | 105 | } 106 | 107 | } 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/controller/CommentController.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.controller; 2 | 3 | import com.codingrecipe.board.dto.CommentDTO; 4 | import com.codingrecipe.board.service.CommentService; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.web.bind.annotation.ModelAttribute; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.ResponseBody; 13 | 14 | import java.util.List; 15 | 16 | @Controller 17 | @RequiredArgsConstructor 18 | @RequestMapping("/comment") 19 | public class CommentController { 20 | private final CommentService commentService; 21 | @PostMapping("/save") 22 | public ResponseEntity save(@ModelAttribute CommentDTO commentDTO) { 23 | System.out.println("commentDTO = " + commentDTO); 24 | Long saveResult = commentService.save(commentDTO); 25 | if (saveResult != null) { 26 | List commentDTOList = commentService.findAll(commentDTO.getBoardId()); 27 | return new ResponseEntity<>(commentDTOList, HttpStatus.OK); 28 | } else { 29 | return new ResponseEntity<>("해당 게시글이 존재하지 않습니다.", HttpStatus.NOT_FOUND); 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/controller/HomeController.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | 6 | @Controller 7 | public class HomeController { 8 | @GetMapping("/") 9 | public String index() { 10 | return "index"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/dto/BoardDTO.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.dto; 2 | 3 | import com.codingrecipe.board.entity.BoardEntity; 4 | import lombok.*; 5 | import org.springframework.web.multipart.MultipartFile; 6 | 7 | import java.time.LocalDateTime; 8 | 9 | // DTO(Data Transfer Object), VO, Bean, Entity 10 | @Getter 11 | @Setter 12 | @ToString 13 | @NoArgsConstructor // 기본생성자 14 | @AllArgsConstructor // 모든 필드를 매개변수로 하는 생성자 15 | public class BoardDTO { 16 | private Long id; 17 | private String boardWriter; 18 | private String boardPass; 19 | private String boardTitle; 20 | private String boardContents; 21 | private int boardHits; 22 | private LocalDateTime boardCreatedTime; 23 | private LocalDateTime boardUpdatedTime; 24 | 25 | private MultipartFile boardFile; // save.html -> Controller 파일 담는 용도 26 | private String originalFileName; // 원본 파일 이름 27 | private String storedFileName; // 서버 저장용 파일 이름 28 | private int fileAttached; // 파일 첨부 여부(첨부 1, 미첨부 0) 29 | 30 | public BoardDTO(Long id, String boardWriter, String boardTitle, int boardHits, LocalDateTime boardCreatedTime) { 31 | this.id = id; 32 | this.boardWriter = boardWriter; 33 | this.boardTitle = boardTitle; 34 | this.boardHits = boardHits; 35 | this.boardCreatedTime = boardCreatedTime; 36 | } 37 | 38 | public static BoardDTO toBoardDTO(BoardEntity boardEntity) { 39 | BoardDTO boardDTO = new BoardDTO(); 40 | boardDTO.setId(boardEntity.getId()); 41 | boardDTO.setBoardWriter(boardEntity.getBoardWriter()); 42 | boardDTO.setBoardPass(boardEntity.getBoardPass()); 43 | boardDTO.setBoardTitle(boardEntity.getBoardTitle()); 44 | boardDTO.setBoardContents(boardEntity.getBoardContents()); 45 | boardDTO.setBoardHits(boardEntity.getBoardHits()); 46 | boardDTO.setBoardCreatedTime(boardEntity.getCreatedTime()); 47 | boardDTO.setBoardUpdatedTime(boardEntity.getUpdatedTime()); 48 | if (boardEntity.getFileAttached() == 0) { 49 | boardDTO.setFileAttached(boardEntity.getFileAttached()); // 0 50 | } else { 51 | boardDTO.setFileAttached(boardEntity.getFileAttached()); // 1 52 | // 파일 이름을 가져가야 함. 53 | // orginalFileName, storedFileName : board_file_table(BoardFileEntity) 54 | // join 55 | // select * from board_table b, board_file_table bf where b.id=bf.board_id 56 | // and where b.id=? 57 | boardDTO.setOriginalFileName(boardEntity.getBoardFileEntityList().get(0).getOriginalFileName()); 58 | boardDTO.setStoredFileName(boardEntity.getBoardFileEntityList().get(0).getStoredFileName()); 59 | } 60 | 61 | return boardDTO; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/dto/CommentDTO.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.dto; 2 | 3 | import com.codingrecipe.board.entity.CommentEntity; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | import lombok.ToString; 7 | 8 | import java.time.LocalDateTime; 9 | 10 | @Getter 11 | @Setter 12 | @ToString 13 | public class CommentDTO { 14 | private Long id; 15 | private String commentWriter; 16 | private String commentContents; 17 | private Long boardId; 18 | private LocalDateTime commentCreatedTime; 19 | 20 | public static CommentDTO toCommentDTO(CommentEntity commentEntity, Long boardId) { 21 | CommentDTO commentDTO = new CommentDTO(); 22 | commentDTO.setId(commentEntity.getId()); 23 | commentDTO.setCommentWriter(commentEntity.getCommentWriter()); 24 | commentDTO.setCommentContents(commentEntity.getCommentContents()); 25 | commentDTO.setCommentCreatedTime(commentEntity.getCreatedTime()); 26 | commentDTO.setBoardId(boardId); 27 | return commentDTO; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/entity/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.entity; 2 | 3 | import lombok.Getter; 4 | import org.hibernate.annotations.CreationTimestamp; 5 | import org.hibernate.annotations.UpdateTimestamp; 6 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 7 | 8 | import javax.persistence.Column; 9 | import javax.persistence.EntityListeners; 10 | import javax.persistence.MappedSuperclass; 11 | import java.time.LocalDateTime; 12 | 13 | @MappedSuperclass 14 | @EntityListeners(AuditingEntityListener.class) 15 | @Getter 16 | public class BaseEntity { 17 | @CreationTimestamp 18 | @Column(updatable = false) 19 | private LocalDateTime createdTime; 20 | 21 | @UpdateTimestamp 22 | @Column(insertable = false) 23 | private LocalDateTime updatedTime; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/entity/BoardEntity.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.entity; 2 | 3 | import com.codingrecipe.board.dto.BoardDTO; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import javax.persistence.*; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | // DB의 테이블 역할을 하는 클래스 12 | @Entity 13 | @Getter 14 | @Setter 15 | @Table(name = "board_table") 16 | public class BoardEntity extends BaseEntity { 17 | @Id // pk 컬럼 지정. 필수 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) // auto_increment 19 | private Long id; 20 | 21 | @Column(length = 20, nullable = false) // 크기 20, not null 22 | private String boardWriter; 23 | 24 | @Column // 크기 255, null 가능 25 | private String boardPass; 26 | 27 | @Column 28 | private String boardTitle; 29 | 30 | @Column(length = 500) 31 | private String boardContents; 32 | 33 | @Column 34 | private int boardHits; 35 | 36 | @Column 37 | private int fileAttached; // 1 or 0 38 | 39 | @OneToMany(mappedBy = "boardEntity", cascade = CascadeType.REMOVE, orphanRemoval = true, fetch = FetchType.LAZY) 40 | private List boardFileEntityList = new ArrayList<>(); 41 | 42 | @OneToMany(mappedBy = "boardEntity", cascade = CascadeType.REMOVE, orphanRemoval = true, fetch = FetchType.LAZY) 43 | private List commentEntityList = new ArrayList<>(); 44 | 45 | public static BoardEntity toSaveEntity(BoardDTO boardDTO) { 46 | BoardEntity boardEntity = new BoardEntity(); 47 | boardEntity.setBoardWriter(boardDTO.getBoardWriter()); 48 | boardEntity.setBoardPass(boardDTO.getBoardPass()); 49 | boardEntity.setBoardTitle(boardDTO.getBoardTitle()); 50 | boardEntity.setBoardContents(boardDTO.getBoardContents()); 51 | boardEntity.setBoardHits(0); 52 | boardEntity.setFileAttached(0); // 파일 없음. 53 | return boardEntity; 54 | } 55 | 56 | public static BoardEntity toUpdateEntity(BoardDTO boardDTO) { 57 | BoardEntity boardEntity = new BoardEntity(); 58 | boardEntity.setId(boardDTO.getId()); 59 | boardEntity.setBoardWriter(boardDTO.getBoardWriter()); 60 | boardEntity.setBoardPass(boardDTO.getBoardPass()); 61 | boardEntity.setBoardTitle(boardDTO.getBoardTitle()); 62 | boardEntity.setBoardContents(boardDTO.getBoardContents()); 63 | boardEntity.setBoardHits(boardDTO.getBoardHits()); 64 | return boardEntity; 65 | } 66 | 67 | public static BoardEntity toSaveFileEntity(BoardDTO boardDTO) { 68 | BoardEntity boardEntity = new BoardEntity(); 69 | boardEntity.setBoardWriter(boardDTO.getBoardWriter()); 70 | boardEntity.setBoardPass(boardDTO.getBoardPass()); 71 | boardEntity.setBoardTitle(boardDTO.getBoardTitle()); 72 | boardEntity.setBoardContents(boardDTO.getBoardContents()); 73 | boardEntity.setBoardHits(0); 74 | boardEntity.setFileAttached(1); // 파일 있음. 75 | return boardEntity; 76 | } 77 | } 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/entity/BoardFileEntity.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.entity; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | 8 | @Entity 9 | @Getter 10 | @Setter 11 | @Table(name = "board_file_table") 12 | public class BoardFileEntity extends BaseEntity { 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.IDENTITY) 15 | private Long id; 16 | 17 | @Column 18 | private String originalFileName; 19 | 20 | @Column 21 | private String storedFileName; 22 | 23 | @ManyToOne(fetch = FetchType.LAZY) 24 | @JoinColumn(name = "board_id") 25 | private BoardEntity boardEntity; 26 | 27 | public static BoardFileEntity toBoardFileEntity(BoardEntity boardEntity, String originalFileName, String storedFileName) { 28 | BoardFileEntity boardFileEntity = new BoardFileEntity(); 29 | boardFileEntity.setOriginalFileName(originalFileName); 30 | boardFileEntity.setStoredFileName(storedFileName); 31 | boardFileEntity.setBoardEntity(boardEntity); 32 | return boardFileEntity; 33 | } 34 | } 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/entity/CommentEntity.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.entity; 2 | 3 | import com.codingrecipe.board.dto.CommentDTO; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import javax.persistence.*; 8 | 9 | @Entity 10 | @Getter 11 | @Setter 12 | @Table(name = "comment_table") 13 | public class CommentEntity extends BaseEntity { 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private Long id; 17 | 18 | @Column(length = 20, nullable = false) 19 | private String commentWriter; 20 | 21 | @Column 22 | private String commentContents; 23 | 24 | /* Board:Comment = 1:N */ 25 | @ManyToOne(fetch = FetchType.LAZY) 26 | @JoinColumn(name = "board_id") 27 | private BoardEntity boardEntity; 28 | 29 | 30 | public static CommentEntity toSaveEntity(CommentDTO commentDTO, BoardEntity boardEntity) { 31 | CommentEntity commentEntity = new CommentEntity(); 32 | commentEntity.setCommentWriter(commentDTO.getCommentWriter()); 33 | commentEntity.setCommentContents(commentDTO.getCommentContents()); 34 | commentEntity.setBoardEntity(boardEntity); 35 | return commentEntity; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/repository/BoardFileRepository.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.repository; 2 | 3 | import com.codingrecipe.board.entity.BoardFileEntity; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface BoardFileRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/repository/BoardRepository.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.repository; 2 | 3 | import com.codingrecipe.board.entity.BoardEntity; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Modifying; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.data.repository.query.Param; 8 | 9 | public interface BoardRepository extends JpaRepository { 10 | // update board_table set board_hits=board_hits+1 where id=? 11 | @Modifying 12 | @Query(value = "update BoardEntity b set b.boardHits=b.boardHits+1 where b.id=:id") 13 | void updateHits(@Param("id") Long id); 14 | } 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/repository/CommentRepository.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.repository; 2 | 3 | import com.codingrecipe.board.entity.BoardEntity; 4 | import com.codingrecipe.board.entity.CommentEntity; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | 7 | import java.util.List; 8 | 9 | public interface CommentRepository extends JpaRepository { 10 | // select * from comment_table where board_id=? order by id desc; 11 | List findAllByBoardEntityOrderByIdDesc(BoardEntity boardEntity); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/service/BoardService.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.service; 2 | 3 | import com.codingrecipe.board.dto.BoardDTO; 4 | import com.codingrecipe.board.entity.BoardEntity; 5 | import com.codingrecipe.board.entity.BoardFileEntity; 6 | import com.codingrecipe.board.repository.BoardFileRepository; 7 | import com.codingrecipe.board.repository.BoardRepository; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.data.domain.Page; 10 | import org.springframework.data.domain.PageRequest; 11 | import org.springframework.data.domain.Pageable; 12 | import org.springframework.data.domain.Sort; 13 | import org.springframework.data.repository.query.Param; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.transaction.annotation.Transactional; 16 | import org.springframework.web.multipart.MultipartFile; 17 | 18 | import java.io.File; 19 | import java.io.IOException; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | import java.util.Optional; 23 | 24 | // DTO -> Entity (Entity Class) 25 | // Entity -> DTO (DTO Class) 26 | 27 | @Service 28 | @RequiredArgsConstructor 29 | public class BoardService { 30 | private final BoardRepository boardRepository; 31 | private final BoardFileRepository boardFileRepository; 32 | public void save(BoardDTO boardDTO) throws IOException { 33 | // 파일 첨부 여부에 따라 로직 분리 34 | if (boardDTO.getBoardFile().isEmpty()) { 35 | // 첨부 파일 없음. 36 | BoardEntity boardEntity = BoardEntity.toSaveEntity(boardDTO); 37 | boardRepository.save(boardEntity); 38 | } else { 39 | // 첨부 파일 있음. 40 | /* 41 | 1. DTO에 담긴 파일을 꺼냄 42 | 2. 파일의 이름 가져옴 43 | 3. 서버 저장용 이름을 만듦 44 | // 내사진.jpg => 839798375892_내사진.jpg 45 | 4. 저장 경로 설정 46 | 5. 해당 경로에 파일 저장 47 | 6. board_table에 해당 데이터 save 처리 48 | 7. board_file_table에 해당 데이터 save 처리 49 | */ 50 | MultipartFile boardFile = boardDTO.getBoardFile(); // 1. 51 | String originalFilename = boardFile.getOriginalFilename(); // 2. 52 | String storedFileName = System.currentTimeMillis() + "_" + originalFilename; // 3. 53 | String savePath = "C:/springboot_img/" + storedFileName; // 4. C:/springboot_img/9802398403948_내사진.jpg 54 | // String savePath = "/Users/사용자이름/springboot_img/" + storedFileName; // C:/springboot_img/9802398403948_내사진.jpg 55 | boardFile.transferTo(new File(savePath)); // 5. 56 | BoardEntity boardEntity = BoardEntity.toSaveFileEntity(boardDTO); 57 | Long savedId = boardRepository.save(boardEntity).getId(); 58 | BoardEntity board = boardRepository.findById(savedId).get(); 59 | 60 | BoardFileEntity boardFileEntity = BoardFileEntity.toBoardFileEntity(board, originalFilename, storedFileName); 61 | boardFileRepository.save(boardFileEntity); 62 | } 63 | 64 | } 65 | 66 | @Transactional 67 | public List findAll() { 68 | List boardEntityList = boardRepository.findAll(); 69 | List boardDTOList = new ArrayList<>(); 70 | for (BoardEntity boardEntity: boardEntityList) { 71 | boardDTOList.add(BoardDTO.toBoardDTO(boardEntity)); 72 | } 73 | return boardDTOList; 74 | } 75 | 76 | @Transactional 77 | public void updateHits(Long id) { 78 | boardRepository.updateHits(id); 79 | } 80 | 81 | @Transactional 82 | public BoardDTO findById(Long id) { 83 | Optional optionalBoardEntity = boardRepository.findById(id); 84 | if (optionalBoardEntity.isPresent()) { 85 | BoardEntity boardEntity = optionalBoardEntity.get(); 86 | BoardDTO boardDTO = BoardDTO.toBoardDTO(boardEntity); 87 | return boardDTO; 88 | } else { 89 | return null; 90 | } 91 | } 92 | 93 | public BoardDTO update(BoardDTO boardDTO) { 94 | BoardEntity boardEntity = BoardEntity.toUpdateEntity(boardDTO); 95 | boardRepository.save(boardEntity); 96 | return findById(boardDTO.getId()); 97 | } 98 | 99 | public void delete(Long id) { 100 | boardRepository.deleteById(id); 101 | } 102 | 103 | public Page paging(Pageable pageable) { 104 | int page = pageable.getPageNumber() - 1; 105 | int pageLimit = 3; // 한 페이지에 보여줄 글 갯수 106 | // 한페이지당 3개씩 글을 보여주고 정렬 기준은 id 기준으로 내림차순 정렬 107 | // page 위치에 있는 값은 0부터 시작 108 | Page boardEntities = 109 | boardRepository.findAll(PageRequest.of(page, pageLimit, Sort.by(Sort.Direction.DESC, "id"))); 110 | 111 | System.out.println("boardEntities.getContent() = " + boardEntities.getContent()); // 요청 페이지에 해당하는 글 112 | System.out.println("boardEntities.getTotalElements() = " + boardEntities.getTotalElements()); // 전체 글갯수 113 | System.out.println("boardEntities.getNumber() = " + boardEntities.getNumber()); // DB로 요청한 페이지 번호 114 | System.out.println("boardEntities.getTotalPages() = " + boardEntities.getTotalPages()); // 전체 페이지 갯수 115 | System.out.println("boardEntities.getSize() = " + boardEntities.getSize()); // 한 페이지에 보여지는 글 갯수 116 | System.out.println("boardEntities.hasPrevious() = " + boardEntities.hasPrevious()); // 이전 페이지 존재 여부 117 | System.out.println("boardEntities.isFirst() = " + boardEntities.isFirst()); // 첫 페이지 여부 118 | System.out.println("boardEntities.isLast() = " + boardEntities.isLast()); // 마지막 페이지 여부 119 | 120 | // 목록: id, writer, title, hits, createdTime 121 | Page boardDTOS = boardEntities.map(board -> new BoardDTO(board.getId(), board.getBoardWriter(), board.getBoardTitle(), board.getBoardHits(), board.getCreatedTime())); 122 | return boardDTOS; 123 | } 124 | } 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /src/main/java/com/codingrecipe/board/service/CommentService.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board.service; 2 | 3 | import com.codingrecipe.board.dto.CommentDTO; 4 | import com.codingrecipe.board.entity.BoardEntity; 5 | import com.codingrecipe.board.entity.CommentEntity; 6 | import com.codingrecipe.board.repository.BoardRepository; 7 | import com.codingrecipe.board.repository.CommentRepository; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.Optional; 14 | 15 | @Service 16 | @RequiredArgsConstructor 17 | public class CommentService { 18 | private final CommentRepository commentRepository; 19 | private final BoardRepository boardRepository; 20 | 21 | public Long save(CommentDTO commentDTO) { 22 | /* 부모엔티티(BoardEntity) 조회 */ 23 | Optional optionalBoardEntity = boardRepository.findById(commentDTO.getBoardId()); 24 | if (optionalBoardEntity.isPresent()) { 25 | BoardEntity boardEntity = optionalBoardEntity.get(); 26 | CommentEntity commentEntity = CommentEntity.toSaveEntity(commentDTO, boardEntity); 27 | return commentRepository.save(commentEntity).getId(); 28 | } else { 29 | return null; 30 | } 31 | } 32 | 33 | public List findAll(Long boardId) { 34 | BoardEntity boardEntity = boardRepository.findById(boardId).get(); 35 | List commentEntityList = commentRepository.findAllByBoardEntityOrderByIdDesc(boardEntity); 36 | /* EntityList -> DTOList */ 37 | List commentDTOList = new ArrayList<>(); 38 | for (CommentEntity commentEntity: commentEntityList) { 39 | CommentDTO commentDTO = CommentDTO.toCommentDTO(commentEntity, boardId); 40 | commentDTOList.add(commentDTO); 41 | } 42 | return commentDTOList; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # 서버 포트 설정 2 | server: 3 | port: 8082 4 | 5 | # database 연동 설정 6 | spring: 7 | datasource: 8 | driver-class-name: com.mysql.cj.jdbc.Driver 9 | url: jdbc:mysql://localhost:3306/db_codingrecipe?serverTimezone=Asia/Seoul&characterEncoding=UTF-8 10 | username: user_codingrecipe 11 | password: 1234 12 | thymeleaf: 13 | cache: false 14 | 15 | # spring data jpa 설정 16 | jpa: 17 | database-platform: org.hibernate.dialect.MySQL5InnoDBDialect 18 | open-in-view: false 19 | show-sql: true 20 | hibernate: 21 | ddl-auto: update -------------------------------------------------------------------------------- /src/main/resources/templates/detail.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | detail 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
id
title
writer
date
hits
contents
image
40 | 41 | 42 | 43 | 44 | 45 |
46 | 47 | 48 | 49 |
50 | 51 | 52 |
53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 |
댓글번호작성자내용작성시간
67 |
68 | 69 | 70 | 128 | -------------------------------------------------------------------------------- /src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | index 6 | 7 | 8 | 9 | 글작성(링크) 10 | 11 | 12 | 13 | 30 | -------------------------------------------------------------------------------- /src/main/resources/templates/list.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | list 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
idtitletitle(||쓰지 않은 경우)writerdatehits
26 | 27 | -------------------------------------------------------------------------------- /src/main/resources/templates/paging.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
idtitlewriterdatehits
26 | 27 | 28 | First 29 | 30 | 31 | prev 32 | 33 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | next 47 | 48 | Last 49 | 50 | 51 | 57 | -------------------------------------------------------------------------------- /src/main/resources/templates/save.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | save 6 | 7 | 8 | 9 | 10 |
11 | writer:
12 | pass:
13 | title:
14 | contents:
15 | file:
16 | 17 |
18 | 19 | -------------------------------------------------------------------------------- /src/main/resources/templates/update.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | update 6 | 7 | 8 |
9 | 10 | writer:
11 | pass:
12 | title:
13 | contents:
14 | 15 | 16 |
17 | 28 | -------------------------------------------------------------------------------- /src/test/java/com/codingrecipe/board/BoardApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.codingrecipe.board; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class BoardApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------