├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── springdatajpa │ │ └── springboot │ │ ├── SpringDataJpaCourseApplication.java │ │ ├── entity │ │ ├── Address.java │ │ ├── Order.java │ │ ├── OrderItem.java │ │ ├── Product.java │ │ ├── ProductCategory.java │ │ ├── Role.java │ │ └── User.java │ │ └── repository │ │ ├── AddressRepository.java │ │ ├── OrderRepository.java │ │ ├── ProductCategoryRepository.java │ │ ├── ProductRepository.java │ │ ├── RoleRepository.java │ │ └── UserRepository.java └── resources │ └── application.properties └── test └── java └── com └── springdatajpa └── springboot ├── SpringDataJpaCourseApplicationTests.java └── repository ├── JPQLQueriesTest.java ├── ManyToManyUnidirectionalTest.java ├── NamedQueriesTest.java ├── NativeSQLQueriesTest.java ├── OneToManyMappingTest.java ├── OneToOneBidirectionalMappingTest.java ├── OneToOneUnidirectionalMappingTest.java ├── PaginationAndSortingTest.java ├── ProductCategoryRepositoryTest.java ├── ProductRepositoryTest.java └── QueryMethodsTest.java /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-jpa-course 2 | Source Code of **Master Spring Data JPA with Hibernate: E-Commerce Project** Udemy course 3 | 4 | # Udemy Course 5 | Master Spring Data JPA with Hibernate: E-Commerce Project 6 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.6.3 9 | 10 | 11 | com.springdatajpa 12 | spring-data-jpa-course 13 | 0.0.1-SNAPSHOT 14 | spring-data-jpa-course 15 | Spring Data JPA with Spring Boot 16 | 17 | 11 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-data-jpa 23 | 24 | 25 | 26 | mysql 27 | mysql-connector-java 28 | runtime 29 | 30 | 31 | 32 | org.projectlombok 33 | lombok 34 | true 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-test 40 | test 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-maven-plugin 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/SpringDataJpaCourseApplication.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringDataJpaCourseApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringDataJpaCourseApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/entity/Address.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | 7 | @Data 8 | @Entity 9 | @Table(name = "addresses") 10 | public class Address { 11 | 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.IDENTITY) 14 | private long id; 15 | private String street; 16 | private String city; 17 | private String state; 18 | private String country; 19 | private String zipCode; 20 | 21 | @OneToOne(cascade = CascadeType.ALL) 22 | @JoinColumn(name = "order_id", referencedColumnName = "id") 23 | private Order order; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/entity/Order.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.entity; 2 | 3 | import lombok.*; 4 | import org.hibernate.annotations.CreationTimestamp; 5 | import org.hibernate.annotations.UpdateTimestamp; 6 | 7 | import javax.persistence.*; 8 | import java.math.BigDecimal; 9 | import java.time.LocalDateTime; 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | 13 | @Data 14 | @Entity 15 | @Table(name = "orders") 16 | public class Order { 17 | 18 | @Id 19 | @GeneratedValue(strategy = GenerationType.IDENTITY) 20 | private long id; 21 | private String orderTrackingNumber; 22 | private int totalQuantity; 23 | private BigDecimal totalPrice; 24 | private String status; 25 | 26 | @CreationTimestamp 27 | private LocalDateTime dateCreated; 28 | @UpdateTimestamp 29 | private LocalDateTime lastUpdated; 30 | 31 | @OneToOne(cascade = CascadeType.ALL, mappedBy = "order") 32 | private Address billingAddress; 33 | 34 | // default fetch type for one to many is LAZY 35 | @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "order") 36 | private Set orderItems = new HashSet<>(); 37 | 38 | public BigDecimal getTotalAmount(){ 39 | BigDecimal amount = new BigDecimal(0.0); 40 | for(OrderItem item: this.orderItems){ 41 | amount = amount.add(item.getPrice()); 42 | } 43 | return amount; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/entity/OrderItem.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.entity; 2 | 3 | import lombok.*; 4 | 5 | import javax.persistence.*; 6 | import java.math.BigDecimal; 7 | 8 | @Getter 9 | @Setter 10 | @NoArgsConstructor 11 | @AllArgsConstructor 12 | @Entity 13 | @Table(name = "order_items") 14 | public class OrderItem { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | private String imageUrl; 20 | private BigDecimal price; 21 | private int quantity; 22 | 23 | @OneToOne 24 | @JoinColumn(name = "product_id") 25 | private Product product; 26 | 27 | @ManyToOne(fetch = FetchType.LAZY) 28 | @JoinColumn(name = "order_id", referencedColumnName = "id") 29 | private Order order; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/entity/Product.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.entity; 2 | 3 | import lombok.*; 4 | import org.hibernate.annotations.CreationTimestamp; 5 | import org.hibernate.annotations.UpdateTimestamp; 6 | 7 | import javax.persistence.*; 8 | import java.math.BigDecimal; 9 | import java.time.LocalDateTime; 10 | 11 | @Entity 12 | @Getter 13 | @Setter 14 | @NoArgsConstructor 15 | @AllArgsConstructor 16 | @ToString 17 | 18 | //@NamedQuery( 19 | // name = "Product.findByPrice", 20 | // query = "SELECT p from Product p where p.price = :price" 21 | //) 22 | 23 | @NamedQueries( 24 | { 25 | @NamedQuery( 26 | name = "Product.findAllOrderByNameDesc", 27 | query = "SELECT p from Product p ORDER By p.name DESC" 28 | ), 29 | @NamedQuery( 30 | name = "Product.findByPrice", 31 | query = "SELECT p from Product p where p.price = :price" 32 | ) 33 | } 34 | ) 35 | 36 | //@NamedNativeQuery( 37 | // name = "Product.findByDescription", 38 | // query = "select * from products p where p.description = :description", 39 | // resultClass = Product.class 40 | //) 41 | 42 | @NamedNativeQueries( 43 | { 44 | @NamedNativeQuery( 45 | name = "Product.findByDescription", 46 | query = "select * from products p where p.description = :description", 47 | resultClass = Product.class 48 | ), 49 | @NamedNativeQuery( 50 | name = "Product.findAllOrderByNameASC", 51 | query = "select * from products order by name asc", 52 | resultClass = Product.class 53 | ) 54 | } 55 | ) 56 | @Table( 57 | name = "products", 58 | schema = "ecommerce", 59 | uniqueConstraints = { 60 | @UniqueConstraint( 61 | name = "sku_unique", 62 | columnNames = "stock_keeping_unit" 63 | ) 64 | } 65 | ) 66 | public class Product { 67 | 68 | @Id 69 | @GeneratedValue( 70 | strategy = GenerationType.SEQUENCE, 71 | generator = "product_generator" 72 | ) 73 | 74 | @SequenceGenerator( 75 | name = "product_generator", 76 | sequenceName = "product_sequence_name", 77 | allocationSize = 1 78 | ) 79 | private Long id; 80 | 81 | @Column(name = "stock_keeping_unit", nullable = false) 82 | private String sku; 83 | 84 | @Column(nullable = false) 85 | private String name; 86 | 87 | private String description; 88 | private BigDecimal price; 89 | private boolean active; 90 | private String imageUrl; 91 | 92 | @CreationTimestamp 93 | private LocalDateTime dateCreated; 94 | 95 | @UpdateTimestamp 96 | private LocalDateTime lastUpdated; 97 | 98 | @ManyToOne 99 | @JoinColumn(name = "category_id", referencedColumnName = "id") 100 | private ProductCategory category; 101 | } -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/entity/ProductCategory.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.entity; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | @Getter 11 | @Setter 12 | @Entity 13 | @Table(name = "product_categories") 14 | public class ProductCategory { 15 | 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | private String categoryName; 20 | private String categoryDescription; 21 | 22 | @OneToMany(cascade = { 23 | CascadeType.PERSIST, 24 | CascadeType.MERGE, 25 | }, fetch = FetchType.LAZY, 26 | mappedBy = "category") 27 | private List products = new ArrayList<>(); 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.entity; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | 8 | @Getter 9 | @Setter 10 | @Entity 11 | @Table(name = "roles") 12 | public class Role { 13 | 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private long id; 17 | private String name; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.entity; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | @Getter 11 | @Setter 12 | @Entity 13 | @Table( 14 | name = "users", 15 | uniqueConstraints = @UniqueConstraint( 16 | name = "unique_email", 17 | columnNames = "email" 18 | ) 19 | ) 20 | public class User { 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private long id; 24 | private String firstName; 25 | private String lastName; 26 | private String email; 27 | private String password; 28 | 29 | @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 30 | @JoinTable( 31 | name = "users_roles", 32 | joinColumns = @JoinColumn( 33 | name = "user_id", referencedColumnName = "id" 34 | ), 35 | inverseJoinColumns = @JoinColumn( 36 | name = "role_id", referencedColumnName = "id" 37 | ) 38 | ) 39 | private Set roles = new HashSet<>(); 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/repository/AddressRepository.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Address; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface AddressRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/repository/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Order; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface OrderRepository extends JpaRepository { 7 | Order findByOrderTrackingNumber(String orderTrackingNumber); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/repository/ProductCategoryRepository.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.ProductCategory; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface ProductCategoryRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/repository/ProductRepository.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Product; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.query.Param; 7 | 8 | import java.math.BigDecimal; 9 | import java.time.LocalDateTime; 10 | import java.util.List; 11 | import java.util.Optional; 12 | 13 | public interface ProductRepository extends JpaRepository { 14 | 15 | /** 16 | * Returns the found product entry by using its name as search 17 | * criteria. If no product entry is found, this method 18 | * returns null. 19 | */ 20 | public Product findByName(String name); 21 | 22 | /** 23 | * Returns an Optional which contains the found product 24 | * entry by using its id as search criteria. If no product entry 25 | * is found, this method returns an empty Optional. 26 | */ 27 | Optional findById(Long id); 28 | 29 | /** 30 | * Returns the found list of product entries whose name or description is given 31 | * as a method parameters. If no product entries is found, this method 32 | * returns an empty list. 33 | */ 34 | List findByNameOrDescription(String name, String description); 35 | 36 | /** 37 | * Returns the found list of product entries whose name and description is given 38 | * as a method parameters. If no product entries is found, this method 39 | * returns an empty list. 40 | */ 41 | List findByNameAndDescription(String name, String description); 42 | 43 | /** 44 | * Return the distinct product entry whose name is given as a method parameter 45 | * If no product entry is found, this method returns null. 46 | */ 47 | Product findDistinctByName(String name); 48 | 49 | /** 50 | * Return the products whose price is greater than given price as method parameter 51 | * @param price 52 | * @return 53 | */ 54 | List findByPriceGreaterThan(BigDecimal price); 55 | 56 | /** 57 | * Return the products whose price is less than given price as method parameter 58 | * @param price 59 | * @return 60 | */ 61 | List findByPriceLessThan(BigDecimal price); 62 | 63 | /** 64 | * Return the filtered the product records that match the given text 65 | * @param name 66 | * @return 67 | */ 68 | List findByNameContaining(String name); 69 | 70 | /** 71 | * Return products based on SQL like condition 72 | * @param name 73 | * @return 74 | */ 75 | List findByNameLike(String name); 76 | 77 | /** 78 | * Returns a products whose price between start price and end price 79 | * @param startPrice 80 | * @param endPrice 81 | * @return 82 | */ 83 | List findByPriceBetween(BigDecimal startPrice, BigDecimal endPrice); 84 | 85 | /** 86 | * Returns a products whose dateCreated between start date and end date 87 | * @param startDate 88 | * @param endDate 89 | * @return 90 | */ 91 | List findByDateCreatedBetween(LocalDateTime startDate, LocalDateTime endDate); 92 | 93 | /** 94 | * Returns list of products based on multiple values 95 | * @param names 96 | * @return 97 | */ 98 | List findByNameIn(List names); 99 | 100 | List findFirst2ByOrderByNameAsc(); 101 | 102 | List findTop2ByOrderByPriceDesc(); 103 | 104 | // Define JPQL query using @Query annotation with index or position parameters 105 | @Query("SELECT p from Product p where p.name = ?1 or p.description = ?2") 106 | Product findByNameOrDescriptionJPQLIndexParam(String name, String description); 107 | 108 | // Define JPQL query using @Query annotation with Named parameters 109 | @Query("SELECT p from Product p where p.name = :name or p.description = :description") 110 | Product findByNameOrDescriptionJPQLNamedParam(@Param("name") String name, 111 | @Param("description") String description); 112 | 113 | // Define Native SQL query using @Query annotation with index or position parameters 114 | @Query(value = "select * from products p where p.name = ?1 or p.description = ?2", nativeQuery = true) 115 | Product findByNameOrDescriptionSQLIndexParam(String name, String description); 116 | 117 | // Define Native SQL query using @Query annotation with Named parameters 118 | @Query(value = "select * from products p where p.name = :name or p.description = :description" 119 | ,nativeQuery = true) 120 | Product findByNameOrDescriptionSQLNamedParam(@Param("name") String name, 121 | @Param("description") String description); 122 | 123 | // Define Named JPQL query 124 | Product findByPrice(@Param("price") BigDecimal price); 125 | 126 | List findAllOrderByNameDesc(); 127 | 128 | // Define Named native SQL query 129 | @Query(nativeQuery = true) 130 | Product findByDescription(@Param("description") String description); 131 | 132 | List findAllOrderByNameASC(); 133 | } 134 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Role; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface RoleRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/springdatajpa/springboot/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface UserRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:mysql://localhost:3306/ecommerce?useSSL=false 2 | spring.datasource.username=root 3 | spring.datasource.password=Mysql@123 4 | 5 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect 6 | 7 | # none, create-only, drop, create, create-drop, validate, update 8 | spring.jpa.hibernate.ddl-auto = update 9 | 10 | spring.jpa.show-sql=true 11 | spring.jpa.properties.hibernate.format_sql=true 12 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/SpringDataJpaCourseApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SpringDataJpaCourseApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/JPQLQueriesTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Product; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | @SpringBootTest 9 | public class JPQLQueriesTest { 10 | 11 | @Autowired 12 | private ProductRepository productRepository; 13 | 14 | @Test 15 | void findByNameOrDescriptionJPQLIndexParamMethod(){ 16 | Product product = productRepository.findByNameOrDescriptionJPQLIndexParam("product 1", 17 | "product 1 description"); 18 | 19 | System.out.println(product.getId()); 20 | System.out.println(product.getName()); 21 | } 22 | 23 | @Test 24 | void findByNameOrDescriptionJPQLNamedParamMethod(){ 25 | 26 | Product product = productRepository.findByNameOrDescriptionJPQLNamedParam("product 1", 27 | "product 1 description"); 28 | 29 | System.out.println(product.getId()); 30 | System.out.println(product.getName()); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/ManyToManyUnidirectionalTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Role; 4 | import com.springdatajpa.springboot.entity.User; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | 9 | @SpringBootTest 10 | public class ManyToManyUnidirectionalTest { 11 | 12 | @Autowired 13 | private UserRepository userRepository; 14 | 15 | @Test 16 | void saveUser(){ 17 | User user = new User(); 18 | user.setFirstName("ramesh"); 19 | user.setLastName("fadatare"); 20 | user.setEmail("ramesh@gmail.com"); 21 | user.setPassword("secrete"); 22 | 23 | Role admin = new Role(); 24 | admin.setName("ROLE_ADMIN"); 25 | 26 | Role customer = new Role(); 27 | customer.setName("ROLE_CUSTOMER"); 28 | 29 | user.getRoles().add(admin); 30 | user.getRoles().add(customer); 31 | 32 | userRepository.save(user); 33 | } 34 | 35 | @Test 36 | void updateUser(){ 37 | User user = userRepository.findById(1L).get(); 38 | user.setFirstName("ram"); 39 | user.setEmail("ram@gmail.com"); 40 | 41 | Role roleUser = new Role(); 42 | roleUser.setName("ROLE_USER"); 43 | 44 | user.getRoles().add(roleUser); 45 | 46 | userRepository.save(user); 47 | } 48 | 49 | @Test 50 | void fetchUser(){ 51 | User user = userRepository.findById(1L).get(); 52 | System.out.println(user.getEmail()); 53 | user.getRoles().forEach((r) -> { 54 | System.out.println(r.getName()); 55 | }); 56 | } 57 | 58 | @Test 59 | void deleteUser(){ 60 | userRepository.deleteById(1L); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/NamedQueriesTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Product; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | import java.math.BigDecimal; 9 | import java.util.List; 10 | 11 | @SpringBootTest 12 | public class NamedQueriesTest { 13 | 14 | @Autowired 15 | private ProductRepository productRepository; 16 | 17 | @Test 18 | void namedJPQLQuery(){ 19 | 20 | Product product = productRepository.findByPrice(new BigDecimal(100)); 21 | 22 | System.out.println(product.getName()); 23 | System.out.println(product.getDescription()); 24 | } 25 | 26 | @Test 27 | void namedJPQLQueries(){ 28 | 29 | List products = productRepository.findAllOrderByNameDesc(); 30 | 31 | products.forEach((p) -> { 32 | System.out.println(p.getName()); 33 | System.out.println(p.getDescription()); 34 | }); 35 | 36 | Product product = productRepository.findByPrice(new BigDecimal(200)); 37 | 38 | System.out.println(product.getName()); 39 | System.out.println(product.getDescription()); 40 | 41 | } 42 | 43 | @Test 44 | void namedNativeSQLQuery(){ 45 | 46 | Product product = productRepository.findByDescription("product 1 description"); 47 | 48 | System.out.println(product.getName()); 49 | System.out.println(product.getDescription()); 50 | 51 | } 52 | 53 | @Test 54 | void namedNativeSQLQueries(){ 55 | Product product = productRepository.findByDescription("product 1 description"); 56 | 57 | System.out.println(product.getName()); 58 | System.out.println(product.getDescription()); 59 | 60 | List products = productRepository.findAllOrderByNameASC(); 61 | 62 | products.forEach((p) ->{ 63 | System.out.println(p.getName()); 64 | System.out.println(p.getDescription()); 65 | }); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/NativeSQLQueriesTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Product; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | @SpringBootTest 9 | public class NativeSQLQueriesTest { 10 | 11 | @Autowired 12 | private ProductRepository productRepository; 13 | 14 | @Test 15 | void findByNameOrDescriptionSQLIndexParamMethod(){ 16 | 17 | Product product = productRepository.findByNameOrDescriptionSQLIndexParam( 18 | "product 1", "product 1 description" 19 | ); 20 | 21 | System.out.println(product.getName()); 22 | System.out.println(product.getDescription()); 23 | } 24 | 25 | @Test 26 | void findByNameOrDescriptionSQLNamedParamMethod(){ 27 | Product product = productRepository.findByNameOrDescriptionSQLNamedParam("product 1" 28 | , "product 1 description"); 29 | System.out.println(product.getName()); 30 | System.out.println(product.getDescription()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/OneToManyMappingTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Address; 4 | import com.springdatajpa.springboot.entity.Order; 5 | import com.springdatajpa.springboot.entity.OrderItem; 6 | import org.junit.jupiter.api.Test; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | 10 | import java.math.BigDecimal; 11 | 12 | @SpringBootTest 13 | public class OneToManyMappingTest { 14 | 15 | @Autowired 16 | private OrderRepository orderRepository; 17 | 18 | @Autowired 19 | private ProductRepository productRepository; 20 | 21 | // save order along with also save it's order items 22 | @Test 23 | void saveOrderMethod(){ 24 | Order order = new Order(); 25 | order.setOrderTrackingNumber("100ABC"); 26 | order.setStatus("In progress"); 27 | 28 | // create order item 1 29 | OrderItem orderItem1 = new OrderItem(); 30 | orderItem1.setProduct(productRepository.findById(1L).get()); 31 | orderItem1.setQuantity(2); 32 | orderItem1.setPrice(orderItem1.getProduct().getPrice().multiply(new BigDecimal(2))); 33 | orderItem1.setImageUrl("image1.png"); 34 | orderItem1.setOrder(order); 35 | order.getOrderItems().add(orderItem1); 36 | 37 | // create order item 2 38 | OrderItem orderItem2 = new OrderItem(); 39 | orderItem2.setProduct(productRepository.findById(2L).get()); 40 | orderItem2.setQuantity(3); 41 | orderItem2.setPrice(orderItem2.getProduct().getPrice().multiply(new BigDecimal(3))); 42 | orderItem2.setImageUrl("image2.png"); 43 | orderItem2.setOrder(order); 44 | order.getOrderItems().add(orderItem2); 45 | 46 | order.setTotalPrice(order.getTotalAmount()); 47 | order.setTotalQuantity(2); 48 | 49 | Address address = new Address(); 50 | address.setCity("Pune"); 51 | address.setStreet("Kothrud"); 52 | address.setState("Maharashtra"); 53 | address.setCountry("India"); 54 | address.setZipCode("411047"); 55 | 56 | order.setBillingAddress(address); 57 | 58 | orderRepository.save(order); 59 | } 60 | 61 | @Test 62 | void fetchOrderMethod(){ 63 | Order order = orderRepository.findById(1L).get(); 64 | System.out.println(order.getStatus()); 65 | System.out.println(order.toString()); 66 | for (OrderItem item: order.getOrderItems()){ 67 | System.out.println(item.getProduct().getName()); 68 | } 69 | } 70 | 71 | @Test 72 | void deleteOrderMethod(){ 73 | orderRepository.deleteById(1L); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/OneToOneBidirectionalMappingTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Address; 4 | import com.springdatajpa.springboot.entity.Order; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | 9 | import java.math.BigDecimal; 10 | 11 | @SpringBootTest 12 | public class OneToOneBidirectionalMappingTest { 13 | 14 | @Autowired 15 | private AddressRepository addressRepository; 16 | 17 | @Test 18 | void saveAddressMethod(){ 19 | 20 | Order order = new Order(); 21 | order.setOrderTrackingNumber("1000ABC"); 22 | order.setTotalQuantity(5); 23 | order.setStatus("IN PROGRESS"); 24 | order.setTotalPrice(new BigDecimal(1000)); 25 | 26 | Address address = new Address(); 27 | address.setCity("Pune"); 28 | address.setStreet("Kothrud"); 29 | address.setState("Maharashtra"); 30 | address.setCountry("India"); 31 | address.setZipCode("411047"); 32 | 33 | order.setBillingAddress(address); 34 | address.setOrder(order); 35 | 36 | addressRepository.save(address); 37 | } 38 | 39 | @Test 40 | void updateAddressMethod(){ 41 | Address address = addressRepository.findById(1L).get(); 42 | address.setZipCode("411048"); 43 | 44 | address.getOrder().setStatus("DELIVERED"); 45 | 46 | addressRepository.save(address); 47 | } 48 | 49 | @Test 50 | void fetchAddressMethod(){ 51 | Address address = addressRepository.findById(1L).get(); 52 | } 53 | 54 | @Test 55 | void deleteAddressMethod(){ 56 | addressRepository.deleteById(1L); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/OneToOneUnidirectionalMappingTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Address; 4 | import com.springdatajpa.springboot.entity.Order; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | 9 | import java.math.BigDecimal; 10 | 11 | @SpringBootTest 12 | public class OneToOneUnidirectionalMappingTest { 13 | 14 | @Autowired 15 | private OrderRepository orderRepository; 16 | 17 | @Test 18 | void saveOrderMethod(){ 19 | Order order = new Order(); 20 | order.setOrderTrackingNumber("1000ABC"); 21 | order.setTotalQuantity(5); 22 | order.setStatus("IN PROGRESS"); 23 | order.setTotalPrice(new BigDecimal(1000)); 24 | 25 | Address address = new Address(); 26 | address.setCity("Pune"); 27 | address.setStreet("Kothrud"); 28 | address.setState("Maharashtra"); 29 | address.setCountry("India"); 30 | address.setZipCode("411047"); 31 | 32 | order.setBillingAddress(address); 33 | 34 | orderRepository.save(order); 35 | 36 | } 37 | 38 | @Test 39 | void getOrderMethod(){ 40 | Order order = orderRepository.findById(2L).get(); 41 | System.out.println(order.toString()); 42 | } 43 | 44 | @Test 45 | void updateOrderMethod(){ 46 | Order order = orderRepository.findById(1L).get(); 47 | order.setStatus("DELIVERED"); 48 | order.getBillingAddress().setZipCode("411087"); 49 | orderRepository.save(order); 50 | } 51 | 52 | @Test 53 | void deleteOrderMethod(){ 54 | orderRepository.deleteById(1L); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/PaginationAndSortingTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Product; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.PageRequest; 9 | import org.springframework.data.domain.Pageable; 10 | import org.springframework.data.domain.Sort; 11 | 12 | import java.util.List; 13 | 14 | @SpringBootTest 15 | public class PaginationAndSortingTest { 16 | 17 | @Autowired 18 | private ProductRepository productRepository; 19 | 20 | @Test 21 | void pagination(){ 22 | 23 | int pageNo = 0; 24 | int pageSize = 5; 25 | 26 | // create pageable object 27 | Pageable pageable = PageRequest.of(pageNo, pageSize); 28 | 29 | // findAll method and pass pageable instance 30 | Page page = productRepository.findAll(pageable); 31 | 32 | List products = page.getContent(); 33 | 34 | products.forEach((p) ->{ 35 | System.out.println(p); 36 | }); 37 | 38 | // total pages 39 | int totalPage = page.getTotalPages(); 40 | // total elements 41 | long totalElements = page.getTotalElements(); 42 | // number of elements 43 | int numberOfElements = page.getNumberOfElements(); 44 | // size 45 | int size = page.getSize(); 46 | 47 | // last 48 | boolean isLast = page.isLast(); 49 | // first 50 | boolean isFirst = page.isFirst(); 51 | System.out.println("total page -> " + totalPage); 52 | System.out.println("totalElements -> " + totalElements); 53 | System.out.println("numberOfElements -> " + numberOfElements); 54 | System.out.println(" size ->" + size); 55 | System.out.println(" isLast -> " + isLast); 56 | System.out.println(" isFirst -> " + isFirst); 57 | } 58 | 59 | @Test 60 | void sorting(){ 61 | 62 | String sortBy = "price"; 63 | String sortDir = "desc"; 64 | 65 | Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name())? 66 | Sort.by(sortBy).ascending(): Sort.by(sortBy).descending(); 67 | 68 | List products = productRepository.findAll(sort); 69 | 70 | products.forEach((p) ->{ 71 | System.out.println(p); 72 | }); 73 | } 74 | 75 | @Test 76 | void sortingByMultipleFields(){ 77 | String sortBy = "name"; 78 | String sortByDesc = "description"; 79 | String sortDir = "desc"; 80 | 81 | Sort sortByName = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name())? 82 | Sort.by(sortBy).ascending(): Sort.by(sortBy).descending(); 83 | 84 | Sort sortByDescription = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name())? 85 | Sort.by(sortByDesc).ascending(): Sort.by(sortByDesc).descending(); 86 | 87 | Sort groupBySort = sortByName.and(sortByDescription); 88 | 89 | List products = productRepository.findAll(groupBySort); 90 | 91 | products.forEach((p) ->{ 92 | System.out.println(p); 93 | }); 94 | } 95 | 96 | @Test 97 | void paginationAndSortingTogether(){ 98 | 99 | String sortBy = "price"; 100 | String sortDir = "desc"; 101 | int pageNo = 1; 102 | int pageSize = 5; 103 | 104 | // Sort object 105 | Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name())? 106 | Sort.by(sortBy).ascending(): Sort.by(sortBy).descending(); 107 | 108 | // Pageable object 109 | Pageable pageable = PageRequest.of(pageNo, pageSize, sort); 110 | 111 | Page page = productRepository.findAll(pageable); 112 | 113 | List products = page.getContent(); 114 | 115 | products.forEach((p) ->{ 116 | System.out.println(p); 117 | }); 118 | 119 | // total pages 120 | int totalPage = page.getTotalPages(); 121 | // total elements 122 | long totalElements = page.getTotalElements(); 123 | // number of elements 124 | int numberOfElements = page.getNumberOfElements(); 125 | // size 126 | int size = page.getSize(); 127 | 128 | // last 129 | boolean isLast = page.isLast(); 130 | // first 131 | boolean isFirst = page.isFirst(); 132 | System.out.println("total page -> " + totalPage); 133 | System.out.println("totalElements -> " + totalElements); 134 | System.out.println("numberOfElements -> " + numberOfElements); 135 | System.out.println(" size ->" + size); 136 | System.out.println(" isLast -> " + isLast); 137 | System.out.println(" isFirst -> " + isFirst); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/ProductCategoryRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Product; 4 | import com.springdatajpa.springboot.entity.ProductCategory; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import java.math.BigDecimal; 11 | 12 | import static org.junit.jupiter.api.Assertions.*; 13 | 14 | @SpringBootTest 15 | class ProductCategoryRepositoryTest { 16 | 17 | @Autowired 18 | private ProductCategoryRepository productCategoryRepository; 19 | 20 | @Test 21 | void saveProductCategory(){ 22 | ProductCategory productCategory = new ProductCategory(); 23 | productCategory.setCategoryName("books"); 24 | productCategory.setCategoryDescription("books description"); 25 | 26 | Product product1 = new Product(); 27 | product1.setName("Core Java"); 28 | product1.setPrice(new BigDecimal(1000)); 29 | product1.setImageUrl("image1.png"); 30 | product1.setSku("ABCD"); 31 | product1.setActive(true); 32 | product1.setCategory(productCategory); 33 | productCategory.getProducts().add(product1); 34 | 35 | Product product2 = new Product(); 36 | product2.setName("Effective Java"); 37 | product2.setPrice(new BigDecimal(2000)); 38 | product2.setImageUrl("image2.png"); 39 | product2.setSku("ABCDE"); 40 | product2.setActive(true); 41 | product2.setCategory(productCategory); 42 | productCategory.getProducts().add(product2); 43 | 44 | productCategoryRepository.save(productCategory); 45 | } 46 | 47 | 48 | @Test 49 | void fetchProductCategory(){ 50 | ProductCategory category = productCategoryRepository.findById(1L).get(); 51 | System.out.println(category); 52 | } 53 | } -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/ProductRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Product; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | 9 | import java.math.BigDecimal; 10 | import java.util.List; 11 | 12 | import static org.junit.jupiter.api.Assertions.*; 13 | 14 | @SpringBootTest 15 | class ProductRepositoryTest { 16 | 17 | @Autowired 18 | private ProductRepository productRepository; 19 | 20 | @Test 21 | void saveMethod(){ 22 | // create product 23 | Product product = new Product(); 24 | product.setName("product 1"); 25 | product.setDescription("product 1 description"); 26 | product.setSku("100ABC"); 27 | product.setPrice(new BigDecimal(100)); 28 | product.setActive(true); 29 | product.setImageUrl("product1.png"); 30 | 31 | // save product 32 | Product savedObject = productRepository.save(product); 33 | 34 | // display product info 35 | System.out.println(savedObject.getId()); 36 | System.out.println(savedObject.toString()); 37 | 38 | } 39 | 40 | @Test 41 | void updateUsingSaveMethod(){ 42 | 43 | // find or retrieve an entity by id 44 | Long id = 1L; 45 | Product product = productRepository.findById(id).get(); 46 | 47 | // update entity information 48 | product.setName("updated product 1"); 49 | product.setDescription("updated product 1 desc"); 50 | 51 | // save updated entity 52 | productRepository.save(product); 53 | } 54 | 55 | @Test 56 | void findByIdMethod(){ 57 | Long id = 1L; 58 | 59 | Product product = productRepository.findById(id).get(); 60 | } 61 | 62 | @Test 63 | void saveAllMethod(){ 64 | 65 | // create product 66 | Product product = new Product(); 67 | product.setName("product 1"); 68 | product.setDescription("product 1 description"); 69 | product.setSku("114ABCD"); 70 | product.setPrice(new BigDecimal(100)); 71 | product.setActive(true); 72 | product.setImageUrl("product1.png"); 73 | 74 | // create product 75 | Product product3 = new Product(); 76 | product3.setName("product 2"); 77 | product3.setDescription("product 2 description"); 78 | product3.setSku("115ABCDE"); 79 | product3.setPrice(new BigDecimal(200)); 80 | product3.setActive(true); 81 | product3.setImageUrl("product2.png"); 82 | 83 | productRepository.saveAll(List.of(product, product3)); 84 | 85 | } 86 | 87 | @Test 88 | void findAllMethod(){ 89 | 90 | List products = productRepository.findAll(); 91 | 92 | products.forEach((p) -> { 93 | System.out.println(p.getName()); 94 | }); 95 | 96 | } 97 | 98 | @Test 99 | void deleteByIdMethod() { 100 | Long id = 1L; 101 | productRepository.deleteById(id); 102 | } 103 | 104 | @Test 105 | void deleteMethod(){ 106 | 107 | // find an entity by id 108 | Long id = 2L; 109 | Product product = productRepository.findById(id).get(); 110 | 111 | // delete(entity) 112 | productRepository.delete(product); 113 | 114 | } 115 | 116 | @Test 117 | void deleteAllMethod(){ 118 | 119 | // productRepository.deleteAll(); 120 | 121 | Product product = productRepository.findById(5L).get(); 122 | 123 | Product product1 = productRepository.findById(6L).get(); 124 | 125 | productRepository.deleteAll(List.of(product, product1)); 126 | 127 | } 128 | 129 | @Test 130 | void existsByIdMethod(){ 131 | Long id = 7L; 132 | 133 | boolean result = productRepository.existsById(id); 134 | 135 | System.out.println(result); 136 | } 137 | 138 | @Test 139 | void countMethod(){ 140 | long count = productRepository.count(); 141 | System.out.println(count); 142 | } 143 | } -------------------------------------------------------------------------------- /src/test/java/com/springdatajpa/springboot/repository/QueryMethodsTest.java: -------------------------------------------------------------------------------- 1 | package com.springdatajpa.springboot.repository; 2 | 3 | import com.springdatajpa.springboot.entity.Product; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | import java.math.BigDecimal; 9 | import java.time.LocalDateTime; 10 | import java.time.format.DateTimeFormatter; 11 | import java.time.format.DateTimeFormatterBuilder; 12 | import java.util.List; 13 | import java.util.Optional; 14 | 15 | @SpringBootTest 16 | public class QueryMethodsTest { 17 | 18 | @Autowired 19 | private ProductRepository productRepository; 20 | 21 | @Test 22 | void findByNameMethod(){ 23 | 24 | Product product = productRepository.findByName("product 2"); 25 | 26 | System.out.println(product.getId()); 27 | System.out.println(product.getName()); 28 | System.out.println(product.getDescription()); 29 | } 30 | 31 | @Test 32 | void findByIdMethod(){ 33 | Product product = productRepository.findById(1L).get(); 34 | 35 | System.out.println(product.getId()); 36 | System.out.println(product.getName()); 37 | System.out.println(product.getDescription()); 38 | } 39 | 40 | @Test 41 | void findByNameOrDescriptionMethod(){ 42 | 43 | List products = productRepository.findByNameOrDescription("product 1", 44 | "product 1 description"); 45 | 46 | products.forEach((p) -> { 47 | System.out.println(p.getId()); 48 | System.out.println(p.getName()); 49 | }); 50 | } 51 | 52 | @Test 53 | void findByNameAndDescriptionMethod(){ 54 | 55 | List products = productRepository.findByNameAndDescription("product 1", 56 | "product 1 description"); 57 | 58 | products.forEach((p) -> { 59 | System.out.println(p.getId()); 60 | System.out.println(p.getName()); 61 | }); 62 | } 63 | 64 | @Test 65 | void findDistinctByNameMethod(){ 66 | 67 | Product product = productRepository.findDistinctByName("product 1"); 68 | System.out.println(product.getId()); 69 | System.out.println(product.getName()); 70 | System.out.println(product.getDescription()); 71 | } 72 | 73 | @Test 74 | void findByPriceGreaterThanMethod(){ 75 | List products = productRepository.findByPriceGreaterThan(new BigDecimal(100)); 76 | products.forEach((p) -> { 77 | System.out.println(p.getId()); 78 | System.out.println(p.getName()); 79 | }); 80 | } 81 | 82 | @Test 83 | void findByPriceLessThanMethod(){ 84 | 85 | List products = productRepository.findByPriceLessThan(new BigDecimal(200)); 86 | products.forEach((p) -> { 87 | System.out.println(p.getId()); 88 | System.out.println(p.getName()); 89 | }); 90 | } 91 | 92 | @Test 93 | void findByNameContainingMethod(){ 94 | 95 | List products = productRepository.findByNameContaining("product 1"); 96 | products.forEach((p) -> { 97 | System.out.println(p.getId()); 98 | System.out.println(p.getName()); 99 | }); 100 | } 101 | 102 | @Test 103 | void findByNameLikeMethod(){ 104 | 105 | List products = productRepository.findByNameLike("product 1"); 106 | products.forEach((p) -> { 107 | System.out.println(p.getId()); 108 | System.out.println(p.getName()); 109 | }); 110 | } 111 | 112 | @Test 113 | void findByPriceBetweenMethod(){ 114 | List products = productRepository.findByPriceBetween( 115 | new BigDecimal(100), new BigDecimal(300) 116 | ); 117 | 118 | products.forEach((p) ->{ 119 | System.out.println(p.getId()); 120 | System.out.println(p.getName()); 121 | }); 122 | 123 | } 124 | 125 | @Test 126 | void findByDateCreatedBetweenMethod(){ 127 | 128 | // start date 129 | LocalDateTime startDate = LocalDateTime.of(2022,02,13,17,48,33); 130 | // end date 131 | LocalDateTime endDate = LocalDateTime.of(2022,02,13,18,15,21); 132 | 133 | List products = productRepository.findByDateCreatedBetween(startDate, endDate); 134 | 135 | products.forEach((p) ->{ 136 | System.out.println(p.getId()); 137 | System.out.println(p.getName()); 138 | }); 139 | } 140 | 141 | @Test 142 | void findByNameInMethod(){ 143 | 144 | List products = productRepository.findByNameIn(List.of("product 1", "product 2", "product 3")); 145 | products.forEach((p) ->{ 146 | System.out.println(p.getId()); 147 | System.out.println(p.getName()); 148 | }); 149 | } 150 | 151 | @Test 152 | void findFirst2ByOrderByNameAscMethod(){ 153 | List products = productRepository.findFirst2ByOrderByNameAsc(); 154 | products.forEach((p) ->{ 155 | System.out.println(p.getId()); 156 | System.out.println(p.getName()); 157 | }); 158 | } 159 | 160 | @Test 161 | void findTop2ByOrderByPriceDescMethod(){ 162 | List products = productRepository.findTop2ByOrderByPriceDesc(); 163 | products.forEach((p) ->{ 164 | System.out.println(p.getId()); 165 | System.out.println(p.getName()); 166 | }); 167 | } 168 | } 169 | --------------------------------------------------------------------------------