├── .gitignore ├── Readme.md ├── jpa-composite-primary-key-demo ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── Readme.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── jpa │ │ │ ├── JpaCompositePrimaryKeyDemoApplication.java │ │ │ ├── model │ │ │ ├── Employee.java │ │ │ └── EmployeeIdentity.java │ │ │ └── repository │ │ │ └── EmployeeRepository.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── jpa │ └── JpaCompositePrimaryKeyDemoApplicationTests.java ├── jpa-element-collection-demo ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── Readme.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── jpa │ │ │ ├── JpaElementCollectionDemoApplication.java │ │ │ ├── model │ │ │ ├── Address.java │ │ │ └── User.java │ │ │ └── repository │ │ │ └── UserRepository.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── jpa │ └── JpaElementCollectionDemoApplicationTests.java ├── jpa-embeddable-demo ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── Readme.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── jpa │ │ │ ├── JpaEmbeddableDemoApplication.java │ │ │ ├── model │ │ │ ├── Address.java │ │ │ ├── Name.java │ │ │ └── User.java │ │ │ └── repository │ │ │ └── UserRepository.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── jpa │ └── JpaEmbeddableDemoApplicationTests.java ├── jpa-many-to-many-demo ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── Readme.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── jpa │ │ │ ├── JpaManyToManyDemoApplication.java │ │ │ ├── model │ │ │ ├── Post.java │ │ │ └── Tag.java │ │ │ └── repository │ │ │ ├── PostRepository.java │ │ │ └── TagRepository.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── jpa │ └── JpaManyToManyDemoApplicationTests.java ├── jpa-one-to-many-demo ├── .gitignore ├── Readme.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── jpa │ │ │ ├── JpaOneToManyDemoApplication.java │ │ │ ├── controller │ │ │ ├── CommentController.java │ │ │ └── PostController.java │ │ │ ├── exception │ │ │ └── ResourceNotFoundException.java │ │ │ ├── model │ │ │ ├── AuditModel.java │ │ │ ├── Comment.java │ │ │ └── Post.java │ │ │ └── repository │ │ │ ├── CommentRepository.java │ │ │ └── PostRepository.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── jpa │ └── JpaOneToManyDemoApplicationTests.java └── jpa-one-to-one-demo ├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── Readme.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── jpa │ │ ├── JpaOneToOneDemoApplication.java │ │ ├── model │ │ ├── Gender.java │ │ ├── User.java │ │ └── UserProfile.java │ │ └── repository │ │ ├── UserProfileRepository.java │ │ └── UserRepository.java └── resources │ └── application.properties └── test └── java └── com └── example └── jpa └── JpaOneToOneDemoApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ 25 | 26 | .DS_Store 27 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | ## Hibernate Tutorials and Demos with Spring Boot and JPA 2 | 3 | 1. [Hibernate One to One Mapping Example with Spring Boot and JPA](https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-one-mapping-example/) 4 | 5 | 6 | 2. [Hibernate One to Many Mapping Example with Spring Boot and JPA](https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/) 7 | 8 | 9 | 3. [Hibernate Many to Many Mapping Example with Spring Boot and JPA](https://www.callicoder.com/hibernate-spring-boot-jpa-many-to-many-mapping-example/) 10 | 11 | 12 | 4. [Hibernate Embeddable Type Example with Spring Boot and JPA](https://www.callicoder.com/hibernate-spring-boot-jpa-embeddable-demo/) 13 | 14 | 15 | 5. [Hibernate Composite Primary Key Example with Spring Boot and JPA](https://www.callicoder.com/hibernate-spring-boot-jpa-composite-primary-key-example/) -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/jpa-hibernate-tutorials/1cca1d2708eb9ed14989f61aa5ea02d4f0cb8268/jpa-composite-primary-key-demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/Readme.md: -------------------------------------------------------------------------------- 1 | # Hibernate Composite Primary Key Example with Spring Boot and JPA 2 | 3 | Read the Tutorial - https://www.callicoder.com/hibernate-spring-boot-jpa-composite-primary-key-example/ 4 | 5 | ## Setup the Application 6 | 7 | 1. Create a database named `hibernate_composite_pk_demo`. 8 | 9 | 2. Open `src/main/resources/application.properties` and change `spring.datasource.username` and `spring.datasource.password` properties as per your MySQL installation. 10 | 11 | 3. Type `mvn spring-boot:run` from the root directory of the project to run the application. -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/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 | # http://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 | # Maven2 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 /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/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 http://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 Maven2 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 key stroke 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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | hibernate-composite-primary-key-demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | hibernate-composite-primary-key-demo 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.5.5 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 11 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-validation 39 | 40 | 41 | mysql 42 | mysql-connector-java 43 | runtime 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/src/main/java/com/example/jpa/JpaCompositePrimaryKeyDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import com.example.jpa.model.Employee; 4 | import com.example.jpa.model.EmployeeIdentity; 5 | import com.example.jpa.repository.EmployeeRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.CommandLineRunner; 8 | import org.springframework.boot.SpringApplication; 9 | import org.springframework.boot.autoconfigure.SpringBootApplication; 10 | 11 | @SpringBootApplication 12 | public class JpaCompositePrimaryKeyDemoApplication implements CommandLineRunner { 13 | 14 | @Autowired 15 | private EmployeeRepository employeeRepository; 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(JpaCompositePrimaryKeyDemoApplication.class, args); 19 | } 20 | 21 | @Override 22 | public void run(String... args) throws Exception { 23 | // Cleanup employees table 24 | employeeRepository.deleteAllInBatch(); 25 | 26 | // Insert a new Employee in the database 27 | Employee employee = new Employee(new EmployeeIdentity("E-123", "D-457"), 28 | "Rajeev Kumar Singh", 29 | "rajeev@callicoder.com", 30 | "+91-9999999999"); 31 | 32 | employeeRepository.save(employee); 33 | 34 | // Retrieving an Employee Record with the composite primary key 35 | employeeRepository.findById(new EmployeeIdentity("E-123", "D-457")); 36 | 37 | // Retrieving all the employees of a particular company 38 | employeeRepository.findByEmployeeIdentityCompanyId("D-457"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/src/main/java/com/example/jpa/model/Employee.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import org.hibernate.annotations.NaturalId; 4 | import javax.persistence.Column; 5 | import javax.persistence.EmbeddedId; 6 | import javax.persistence.Entity; 7 | import javax.persistence.Table; 8 | import javax.validation.constraints.Email; 9 | import javax.validation.constraints.NotNull; 10 | import javax.validation.constraints.Size; 11 | 12 | /** 13 | * Created by rajeevkumarsingh on 22/11/17. 14 | */ 15 | @Entity 16 | @Table(name = "employees") 17 | public class Employee { 18 | 19 | @EmbeddedId 20 | private EmployeeIdentity employeeIdentity; 21 | 22 | @NotNull 23 | @Size(max = 60) 24 | private String name; 25 | 26 | @NaturalId 27 | @NotNull 28 | @Email 29 | @Size(max = 60) 30 | private String email; 31 | 32 | @Size(max = 15) 33 | @Column(name = "phone_number", unique = true) 34 | private String phoneNumber; 35 | 36 | public Employee() { 37 | 38 | } 39 | 40 | public Employee(EmployeeIdentity employeeIdentity, String name, String email, String phoneNumber) { 41 | this.employeeIdentity = employeeIdentity; 42 | this.name = name; 43 | this.email = email; 44 | this.phoneNumber = phoneNumber; 45 | } 46 | 47 | public EmployeeIdentity getEmployeeIdentity() { 48 | return employeeIdentity; 49 | } 50 | 51 | public void setEmployeeIdentity(EmployeeIdentity employeeIdentity) { 52 | this.employeeIdentity = employeeIdentity; 53 | } 54 | 55 | public String getName() { 56 | return name; 57 | } 58 | 59 | public void setName(String name) { 60 | this.name = name; 61 | } 62 | 63 | public String getEmail() { 64 | return email; 65 | } 66 | 67 | public void setEmail(String email) { 68 | this.email = email; 69 | } 70 | 71 | public String getPhoneNumber() { 72 | return phoneNumber; 73 | } 74 | 75 | public void setPhoneNumber(String phoneNumber) { 76 | this.phoneNumber = phoneNumber; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/src/main/java/com/example/jpa/model/EmployeeIdentity.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.Embeddable; 4 | import javax.validation.constraints.NotNull; 5 | import javax.validation.constraints.Size; 6 | import java.io.Serializable; 7 | 8 | /** 9 | * Created by rajeevkumarsingh on 22/11/17. 10 | */ 11 | @Embeddable 12 | public class EmployeeIdentity implements Serializable { 13 | @NotNull 14 | @Size(max = 20) 15 | private String employeeId; 16 | 17 | @NotNull 18 | @Size(max = 20) 19 | private String companyId; 20 | 21 | public EmployeeIdentity() { 22 | 23 | } 24 | 25 | public EmployeeIdentity(String employeeId, String companyId) { 26 | this.employeeId = employeeId; 27 | this.companyId = companyId; 28 | } 29 | 30 | public String getEmployeeId() { 31 | return employeeId; 32 | } 33 | 34 | public void setEmployeeId(String employeeId) { 35 | this.employeeId = employeeId; 36 | } 37 | 38 | public String getCompanyId() { 39 | return companyId; 40 | } 41 | 42 | public void setCompanyId(String companyId) { 43 | this.companyId = companyId; 44 | } 45 | 46 | @Override 47 | public boolean equals(Object o) { 48 | if (this == o) return true; 49 | if (o == null || getClass() != o.getClass()) return false; 50 | 51 | EmployeeIdentity that = (EmployeeIdentity) o; 52 | 53 | if (!employeeId.equals(that.employeeId)) return false; 54 | return companyId.equals(that.companyId); 55 | } 56 | 57 | @Override 58 | public int hashCode() { 59 | int result = employeeId.hashCode(); 60 | result = 31 * result + companyId.hashCode(); 61 | return result; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/src/main/java/com/example/jpa/repository/EmployeeRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.Employee; 4 | import com.example.jpa.model.EmployeeIdentity; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | 10 | 11 | /** 12 | * Created by rajeevkumarsingh on 22/11/17. 13 | */ 14 | @Repository 15 | public interface EmployeeRepository extends JpaRepository { 16 | List findByEmployeeIdentityCompanyId(String companyId); 17 | } 18 | -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) 2 | spring.datasource.url=jdbc:mysql://localhost:3306/jpa_composite_pk_demo?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false 3 | spring.datasource.username=root 4 | spring.datasource.password=callicoder 5 | 6 | # Hibernate 7 | 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 10 | 11 | # Hibernate ddl auto (create, create-drop, validate, update) 12 | spring.jpa.hibernate.ddl-auto = update 13 | 14 | logging.level.org.hibernate.SQL=DEBUG 15 | logging.level.org.hibernate.type=TRACE -------------------------------------------------------------------------------- /jpa-composite-primary-key-demo/src/test/java/com/example/jpa/JpaCompositePrimaryKeyDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class JpaCompositePrimaryKeyDemoApplicationTests { 8 | 9 | @Test 10 | public void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /jpa-element-collection-demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/jpa-hibernate-tutorials/1cca1d2708eb9ed14989f61aa5ea02d4f0cb8268/jpa-element-collection-demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /jpa-element-collection-demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/Readme.md: -------------------------------------------------------------------------------- 1 | # Hibernate ElementCollection Mapping Example with Spring Boot and JPA 2 | 3 | Read the Tutorial - https://www.callicoder.com/hibernate-spring-boot-jpa-element-collection-demo/ 4 | 5 | ## Setup the Application 6 | 7 | 1. Create a database named `hibernate_element_collection_demo`. 8 | 9 | 2. Open `src/main/resources/application.properties` and change `spring.datasource.username` and `spring.datasource.password` properties as per your MySQL installation. 10 | 11 | 3. Type `mvn spring-boot:run` from the root directory of the project to run the application. -------------------------------------------------------------------------------- /jpa-element-collection-demo/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 | # http://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 | # Maven2 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 /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/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 http://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 Maven2 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 key stroke 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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | hibernate-element-collection-demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | hibernate-element-collection-demo 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.5.5 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-validation 39 | 40 | 41 | mysql 42 | mysql-connector-java 43 | runtime 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/src/main/java/com/example/jpa/JpaElementCollectionDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import com.example.jpa.model.Address; 4 | import com.example.jpa.model.User; 5 | import com.example.jpa.repository.UserRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.CommandLineRunner; 8 | import org.springframework.boot.SpringApplication; 9 | import org.springframework.boot.autoconfigure.SpringBootApplication; 10 | 11 | import java.util.HashSet; 12 | import java.util.Set; 13 | 14 | @SpringBootApplication 15 | public class JpaElementCollectionDemoApplication implements CommandLineRunner { 16 | 17 | @Autowired 18 | private UserRepository userRepository; 19 | 20 | public static void main(String[] args) { 21 | SpringApplication.run(JpaElementCollectionDemoApplication.class, args); 22 | } 23 | 24 | @Override 25 | public void run(String... args) throws Exception { 26 | // Cleanup database tables. 27 | userRepository.deleteAll(); 28 | 29 | // Insert a user with multiple phone numbers and addresses. 30 | Set phoneNumbers = new HashSet<>(); 31 | phoneNumbers.add("+91-9999999999"); 32 | phoneNumbers.add("+91-9898989898"); 33 | 34 | Set
addresses = new HashSet<>(); 35 | addresses.add(new Address("747", "Golf View Road", "Bangalore", 36 | "Karnataka", "India", "560008")); 37 | addresses.add(new Address("Plot No 44", "Electronic City", "Bangalore", 38 | "Karnataka", "India", "560001")); 39 | 40 | User user = new User("Rajeev Kumar Singh", "rajeev@callicoder.com", 41 | phoneNumbers, addresses); 42 | 43 | userRepository.save(user); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/src/main/java/com/example/jpa/model/Address.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.Embeddable; 4 | import javax.validation.constraints.NotNull; 5 | import javax.validation.constraints.Size; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 22/11/17. 9 | */ 10 | @Embeddable 11 | public class Address { 12 | @NotNull 13 | @Size(max = 100) 14 | private String addressLine1; 15 | 16 | @NotNull 17 | @Size(max = 100) 18 | private String addressLine2; 19 | 20 | @NotNull 21 | @Size(max = 100) 22 | private String city; 23 | 24 | @NotNull 25 | @Size(max = 100) 26 | private String state; 27 | 28 | @NotNull 29 | @Size(max = 100) 30 | private String country; 31 | 32 | @NotNull 33 | @Size(max = 100) 34 | private String zipCode; 35 | 36 | public Address() { 37 | 38 | } 39 | 40 | public Address(String addressLine1, String addressLine2, String city, 41 | String state, String country, String zipCode) { 42 | this.addressLine1 = addressLine1; 43 | this.addressLine2 = addressLine2; 44 | this.city = city; 45 | this.state = state; 46 | this.country = country; 47 | this.zipCode = zipCode; 48 | } 49 | 50 | public String getAddressLine1() { 51 | return addressLine1; 52 | } 53 | 54 | public void setAddressLine1(String addressLine1) { 55 | this.addressLine1 = addressLine1; 56 | } 57 | 58 | public String getAddressLine2() { 59 | return addressLine2; 60 | } 61 | 62 | public void setAddressLine2(String addressLine2) { 63 | this.addressLine2 = addressLine2; 64 | } 65 | 66 | public String getCity() { 67 | return city; 68 | } 69 | 70 | public void setCity(String city) { 71 | this.city = city; 72 | } 73 | 74 | public String getState() { 75 | return state; 76 | } 77 | 78 | public void setState(String state) { 79 | this.state = state; 80 | } 81 | 82 | public String getCountry() { 83 | return country; 84 | } 85 | 86 | public void setCountry(String country) { 87 | this.country = country; 88 | } 89 | 90 | public String getZipCode() { 91 | return zipCode; 92 | } 93 | 94 | public void setZipCode(String zipCode) { 95 | this.zipCode = zipCode; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/src/main/java/com/example/jpa/model/User.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.*; 4 | import javax.validation.constraints.Email; 5 | import javax.validation.constraints.NotNull; 6 | import javax.validation.constraints.Size; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | /** 11 | * Created by rajeevkumarsingh on 22/11/17. 12 | */ 13 | @Entity 14 | @Table(name = "users") 15 | public class User { 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private Long id; 19 | 20 | @NotNull 21 | @Size(max = 100) 22 | private String name; 23 | 24 | @NotNull 25 | @Email 26 | @Size(max = 100) 27 | @Column(unique = true) 28 | private String email; 29 | 30 | @ElementCollection 31 | @CollectionTable(name = "user_phone_numbers", joinColumns = @JoinColumn(name = "user_id")) 32 | @Column(name = "phone_number") 33 | private Set phoneNumbers = new HashSet<>(); 34 | 35 | @ElementCollection(fetch = FetchType.LAZY) 36 | @CollectionTable(name = "user_addresses", joinColumns = @JoinColumn(name = "user_id")) 37 | @AttributeOverrides({ 38 | @AttributeOverride(name = "addressLine1", column = @Column(name = "house_number")), 39 | @AttributeOverride(name = "addressLine2", column = @Column(name = "street")) 40 | }) 41 | private Set
addresses = new HashSet<>(); 42 | 43 | 44 | public User() { 45 | 46 | } 47 | 48 | public User(String name, String email, Set phoneNumbers, Set
addresses) { 49 | this.name = name; 50 | this.email = email; 51 | this.phoneNumbers = phoneNumbers; 52 | this.addresses = addresses; 53 | } 54 | 55 | public Long getId() { 56 | return id; 57 | } 58 | 59 | public void setId(Long id) { 60 | this.id = id; 61 | } 62 | 63 | public String getName() { 64 | return name; 65 | } 66 | 67 | public void setName(String name) { 68 | this.name = name; 69 | } 70 | 71 | public String getEmail() { 72 | return email; 73 | } 74 | 75 | public void setEmail(String email) { 76 | this.email = email; 77 | } 78 | 79 | public Set getPhoneNumbers() { 80 | return phoneNumbers; 81 | } 82 | 83 | public void setPhoneNumbers(Set phoneNumbers) { 84 | this.phoneNumbers = phoneNumbers; 85 | } 86 | 87 | public Set
getAddresses() { 88 | return addresses; 89 | } 90 | 91 | public void setAddresses(Set
addresses) { 92 | this.addresses = addresses; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/src/main/java/com/example/jpa/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 22/11/17. 9 | */ 10 | @Repository 11 | public interface UserRepository extends JpaRepository { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-element-collection-demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) 2 | spring.datasource.url=jdbc:mysql://localhost:3306/jpa_element_collection_demo?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false 3 | spring.datasource.username=root 4 | spring.datasource.password=callicoder 5 | 6 | # Hibernate 7 | 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 10 | 11 | # Hibernate ddl auto (create, create-drop, validate, update) 12 | spring.jpa.hibernate.ddl-auto = update 13 | 14 | logging.level.org.hibernate.SQL=DEBUG 15 | logging.level.org.hibernate.type=TRACE -------------------------------------------------------------------------------- /jpa-element-collection-demo/src/test/java/com/example/jpa/JpaElementCollectionDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class JpaElementCollectionDemoApplicationTests { 8 | 9 | @Test 10 | public void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /jpa-embeddable-demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/jpa-hibernate-tutorials/1cca1d2708eb9ed14989f61aa5ea02d4f0cb8268/jpa-embeddable-demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /jpa-embeddable-demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/Readme.md: -------------------------------------------------------------------------------- 1 | # Hibernate Embeddable Type Example with Spring Boot and JPA 2 | 3 | Read the Tutorial - https://www.callicoder.com/hibernate-spring-boot-jpa-embeddable-demo/ 4 | 5 | ## Setup the Application 6 | 7 | 1. Create a database named `hibernate_embeddable_demo`. 8 | 9 | 2. Open `src/main/resources/application.properties` and change `spring.datasource.username` and `spring.datasource.password` properties as per your MySQL installation. 10 | 11 | 3. Type `mvn spring-boot:run` from the root directory of the project to run the application. -------------------------------------------------------------------------------- /jpa-embeddable-demo/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 | # http://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 | # Maven2 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 /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/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 http://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 Maven2 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 key stroke 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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | hibernate-embeddable-demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | hibernate-embeddable-demo 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.5.5 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 11 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-validation 39 | 40 | 41 | mysql 42 | mysql-connector-java 43 | runtime 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/src/main/java/com/example/jpa/JpaEmbeddableDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import com.example.jpa.model.Address; 4 | import com.example.jpa.model.Name; 5 | import com.example.jpa.model.User; 6 | import com.example.jpa.repository.UserRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.CommandLineRunner; 9 | import org.springframework.boot.SpringApplication; 10 | import org.springframework.boot.autoconfigure.SpringBootApplication; 11 | 12 | @SpringBootApplication 13 | public class JpaEmbeddableDemoApplication implements CommandLineRunner { 14 | 15 | @Autowired 16 | private UserRepository userRepository; 17 | 18 | public static void main(String[] args) { 19 | SpringApplication.run(JpaEmbeddableDemoApplication.class, args); 20 | } 21 | 22 | @Override 23 | public void run(String... args) throws Exception { 24 | userRepository.deleteAllInBatch(); 25 | 26 | Name name = new Name("Rajeev", "Kumar", "Singh"); 27 | Address address = new Address("747", "Golf View Road", "Bangalore", "Karnataka", "India", "560008"); 28 | User user = new User(name, "rajeev@callicoder.com", address); 29 | 30 | userRepository.save(user); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/src/main/java/com/example/jpa/model/Address.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.Embeddable; 4 | import javax.validation.constraints.NotNull; 5 | import javax.validation.constraints.Size; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 22/11/17. 9 | */ 10 | @Embeddable 11 | public class Address { 12 | @NotNull 13 | @Size(max = 100) 14 | private String addressLine1; 15 | 16 | @NotNull 17 | @Size(max = 100) 18 | private String addressLine2; 19 | 20 | @NotNull 21 | @Size(max = 100) 22 | private String city; 23 | 24 | @NotNull 25 | @Size(max = 100) 26 | private String state; 27 | 28 | @NotNull 29 | @Size(max = 100) 30 | private String country; 31 | 32 | @NotNull 33 | @Size(max = 6) 34 | private String zipCode; 35 | 36 | 37 | public Address() { 38 | 39 | } 40 | 41 | public Address(String addressLine1, String addressLine2, String city, 42 | String state, String country, String zipCode) { 43 | this.addressLine1 = addressLine1; 44 | this.addressLine2 = addressLine2; 45 | this.city = city; 46 | this.state = state; 47 | this.country = country; 48 | this.zipCode = zipCode; 49 | } 50 | 51 | public String getAddressLine1() { 52 | return addressLine1; 53 | } 54 | 55 | public void setAddressLine1(String addressLine1) { 56 | this.addressLine1 = addressLine1; 57 | } 58 | 59 | public String getAddressLine2() { 60 | return addressLine2; 61 | } 62 | 63 | public void setAddressLine2(String addressLine2) { 64 | this.addressLine2 = addressLine2; 65 | } 66 | 67 | public String getCity() { 68 | return city; 69 | } 70 | 71 | public void setCity(String city) { 72 | this.city = city; 73 | } 74 | 75 | public String getState() { 76 | return state; 77 | } 78 | 79 | public void setState(String state) { 80 | this.state = state; 81 | } 82 | 83 | public String getCountry() { 84 | return country; 85 | } 86 | 87 | public void setCountry(String country) { 88 | this.country = country; 89 | } 90 | 91 | public String getZipCode() { 92 | return zipCode; 93 | } 94 | 95 | public void setZipCode(String zipCode) { 96 | this.zipCode = zipCode; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/src/main/java/com/example/jpa/model/Name.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.Embeddable; 4 | import javax.validation.constraints.NotNull; 5 | import javax.validation.constraints.Size; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 22/11/17. 9 | */ 10 | @Embeddable 11 | public class Name { 12 | @NotNull 13 | @Size(max = 40) 14 | private String firstName; 15 | 16 | @Size(max = 40) 17 | private String middleName; 18 | 19 | @Size(max = 40) 20 | private String lastName; 21 | 22 | public Name() { 23 | 24 | } 25 | 26 | public Name(String firstName, String middleName, String lastName) { 27 | this.firstName = firstName; 28 | this.middleName = middleName; 29 | this.lastName = lastName; 30 | } 31 | 32 | public String getFirstName() { 33 | return firstName; 34 | } 35 | 36 | public void setFirstName(String firstName) { 37 | this.firstName = firstName; 38 | } 39 | 40 | public String getMiddleName() { 41 | return middleName; 42 | } 43 | 44 | public void setMiddleName(String middleName) { 45 | this.middleName = middleName; 46 | } 47 | 48 | public String getLastName() { 49 | return lastName; 50 | } 51 | 52 | public void setLastName(String lastName) { 53 | this.lastName = lastName; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/src/main/java/com/example/jpa/model/User.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import org.hibernate.validator.constraints.Email; 4 | 5 | import javax.persistence.*; 6 | import javax.validation.constraints.NotNull; 7 | 8 | /** 9 | * Created by rajeevkumarsingh on 22/11/17. 10 | */ 11 | @Entity 12 | @Table(name = "users") 13 | public class User { 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private Long id; 17 | 18 | @Embedded 19 | private Name name; 20 | 21 | @NotNull 22 | @Email 23 | @Column(unique = true) 24 | private String email; 25 | 26 | @Embedded 27 | @AttributeOverrides(value = { 28 | @AttributeOverride(name = "addressLine1", column = @Column(name = "house_number")), 29 | @AttributeOverride(name = "addressLine2", column = @Column(name = "street")) 30 | }) 31 | private Address address; 32 | 33 | public User() { 34 | 35 | } 36 | 37 | public User(Name name, String email, Address address) { 38 | this.name = name; 39 | this.email = email; 40 | this.address = address; 41 | } 42 | 43 | public Long getId() { 44 | return id; 45 | } 46 | 47 | public void setId(Long id) { 48 | this.id = id; 49 | } 50 | 51 | public Name getName() { 52 | return name; 53 | } 54 | 55 | public void setName(Name name) { 56 | this.name = name; 57 | } 58 | 59 | public String getEmail() { 60 | return email; 61 | } 62 | 63 | public void setEmail(String email) { 64 | this.email = email; 65 | } 66 | 67 | public Address getAddress() { 68 | return address; 69 | } 70 | 71 | public void setAddress(Address address) { 72 | this.address = address; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/src/main/java/com/example/jpa/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.Name; 4 | import com.example.jpa.model.User; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | 10 | 11 | /** 12 | * Created by rajeevkumarsingh on 22/11/17. 13 | */ 14 | @Repository 15 | public interface UserRepository extends JpaRepository { 16 | User findByEmail(String email); 17 | 18 | List findByName(Name name); 19 | 20 | List findByNameFirstName(String firstName); 21 | 22 | List findByAddressCountry(String country); 23 | } 24 | -------------------------------------------------------------------------------- /jpa-embeddable-demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) 2 | spring.datasource.url=jdbc:mysql://localhost:3306/jpa_embeddable_demo?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false 3 | spring.datasource.username=root 4 | spring.datasource.password=callicoder 5 | 6 | # Hibernate 7 | 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 10 | 11 | # Hibernate ddl auto (create, create-drop, validate, update) 12 | spring.jpa.hibernate.ddl-auto = update 13 | 14 | logging.level.org.hibernate.SQL=DEBUG 15 | logging.level.org.hibernate.type=TRACE -------------------------------------------------------------------------------- /jpa-embeddable-demo/src/test/java/com/example/jpa/JpaEmbeddableDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class JpaEmbeddableDemoApplicationTests { 8 | 9 | @Test 10 | public void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /jpa-many-to-many-demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/jpa-hibernate-tutorials/1cca1d2708eb9ed14989f61aa5ea02d4f0cb8268/jpa-many-to-many-demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /jpa-many-to-many-demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/Readme.md: -------------------------------------------------------------------------------- 1 | # Hibernate Many to Many Mapping Example with Spring Boot and JPA 2 | 3 | Read the Tutorial - https://www.callicoder.com/hibernate-spring-boot-jpa-many-to-many-mapping-example/ 4 | 5 | ## Setup the Application 6 | 7 | 1. Create a database named `hibernate_many_to_many_demo`. 8 | 9 | 2. Open `src/main/resources/application.properties` and change `spring.datasource.username` and `spring.datasource.password` properties as per your MySQL installation. 10 | 11 | 3. Type `mvn spring-boot:run` from the root directory of the project to run the application. -------------------------------------------------------------------------------- /jpa-many-to-many-demo/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 | # http://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 | # Maven2 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 /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/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 http://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 Maven2 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 key stroke 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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | hibernate-many-to-many-demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | hibernate-many-to-many-demo 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.5.5 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-validation 39 | 40 | 41 | mysql 42 | mysql-connector-java 43 | runtime 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/src/main/java/com/example/jpa/JpaManyToManyDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import com.example.jpa.model.Post; 4 | import com.example.jpa.model.Tag; 5 | import com.example.jpa.repository.PostRepository; 6 | import com.example.jpa.repository.TagRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.CommandLineRunner; 9 | import org.springframework.boot.SpringApplication; 10 | import org.springframework.boot.autoconfigure.SpringBootApplication; 11 | 12 | @SpringBootApplication 13 | public class JpaManyToManyDemoApplication implements CommandLineRunner { 14 | 15 | @Autowired 16 | private TagRepository tagRepository; 17 | 18 | @Autowired 19 | private PostRepository postRepository; 20 | 21 | public static void main(String[] args) { 22 | SpringApplication.run(JpaManyToManyDemoApplication.class, args); 23 | } 24 | 25 | @Override 26 | public void run(String... args) throws Exception { 27 | // Cleanup the tables 28 | postRepository.deleteAllInBatch(); 29 | tagRepository.deleteAllInBatch(); 30 | 31 | // ======================================= 32 | 33 | // Create a Post 34 | Post post = new Post("Hibernate Many to Many Example with Spring Boot", 35 | "Learn how to map a many to many relationship using hibernate", 36 | "Entire Post content with Sample code"); 37 | 38 | // Create two tags 39 | Tag tag1 = new Tag("Spring Boot"); 40 | Tag tag2 = new Tag("Hibernate"); 41 | 42 | 43 | // Add tag references in the post 44 | post.getTags().add(tag1); 45 | post.getTags().add(tag2); 46 | 47 | // Add post reference in the tags 48 | tag1.getPosts().add(post); 49 | tag2.getPosts().add(post); 50 | 51 | postRepository.save(post); 52 | 53 | // ======================================= 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/src/main/java/com/example/jpa/model/Post.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.*; 4 | import javax.validation.constraints.NotNull; 5 | import javax.validation.constraints.Size; 6 | import java.util.Date; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | /** 11 | * Created by rajeevkumarsingh on 23/11/17. 12 | */ 13 | @Entity 14 | @Table(name = "posts") 15 | public class Post { 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private Long id; 19 | 20 | @NotNull 21 | @Size(max = 100) 22 | @Column(unique = true) 23 | private String title; 24 | 25 | @NotNull 26 | @Size(max = 250) 27 | private String description; 28 | 29 | @NotNull 30 | @Lob 31 | private String content; 32 | 33 | @NotNull 34 | @Temporal(TemporalType.TIMESTAMP) 35 | @Column(name = "posted_at") 36 | private Date postedAt = new Date(); 37 | 38 | @NotNull 39 | @Temporal(TemporalType.TIMESTAMP) 40 | @Column(name = "last_updated_at") 41 | private Date lastUpdatedAt = new Date(); 42 | 43 | 44 | @ManyToMany(fetch = FetchType.LAZY, 45 | cascade = { 46 | CascadeType.PERSIST, 47 | CascadeType.MERGE 48 | }) 49 | @JoinTable(name = "post_tags", 50 | joinColumns = { @JoinColumn(name = "post_id") }, 51 | inverseJoinColumns = { @JoinColumn(name = "tag_id") }) 52 | private Set tags = new HashSet<>(); 53 | 54 | 55 | public Post() { 56 | 57 | } 58 | 59 | public Post(String title, String description, String content) { 60 | this.title = title; 61 | this.description = description; 62 | this.content = content; 63 | } 64 | 65 | public Long getId() { 66 | return id; 67 | } 68 | 69 | public void setId(Long id) { 70 | this.id = id; 71 | } 72 | 73 | public String getTitle() { 74 | return title; 75 | } 76 | 77 | public void setTitle(String title) { 78 | this.title = title; 79 | } 80 | 81 | public String getDescription() { 82 | return description; 83 | } 84 | 85 | public void setDescription(String description) { 86 | this.description = description; 87 | } 88 | 89 | public String getContent() { 90 | return content; 91 | } 92 | 93 | public void setContent(String content) { 94 | this.content = content; 95 | } 96 | 97 | public Date getPostedAt() { 98 | return postedAt; 99 | } 100 | 101 | public void setPostedAt(Date postedAt) { 102 | this.postedAt = postedAt; 103 | } 104 | 105 | public Date getLastUpdatedAt() { 106 | return lastUpdatedAt; 107 | } 108 | 109 | public void setLastUpdatedAt(Date lastUpdatedAt) { 110 | this.lastUpdatedAt = lastUpdatedAt; 111 | } 112 | 113 | public Set getTags() { 114 | return tags; 115 | } 116 | 117 | public void setTags(Set tags) { 118 | this.tags = tags; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/src/main/java/com/example/jpa/model/Tag.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import org.hibernate.annotations.NaturalId; 4 | 5 | import javax.persistence.*; 6 | import javax.validation.constraints.NotNull; 7 | import javax.validation.constraints.Size; 8 | import java.util.HashSet; 9 | import java.util.Set; 10 | 11 | /** 12 | * Created by rajeevkumarsingh on 23/11/17. 13 | */ 14 | @Entity 15 | @Table(name = "tags") 16 | public class Tag { 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private Long id; 20 | 21 | @NotNull 22 | @Size(max = 100) 23 | @NaturalId 24 | private String name; 25 | 26 | @ManyToMany(fetch = FetchType.LAZY, 27 | cascade = { 28 | CascadeType.PERSIST, 29 | CascadeType.MERGE 30 | }, 31 | mappedBy = "tags") 32 | private Set posts = new HashSet<>(); 33 | 34 | public Tag() { 35 | 36 | } 37 | 38 | public Tag(String name) { 39 | this.name = name; 40 | } 41 | 42 | public Long getId() { 43 | return id; 44 | } 45 | 46 | public void setId(Long id) { 47 | this.id = id; 48 | } 49 | 50 | public String getName() { 51 | return name; 52 | } 53 | 54 | public void setName(String name) { 55 | this.name = name; 56 | } 57 | 58 | public Set getPosts() { 59 | return posts; 60 | } 61 | 62 | public void setPosts(Set posts) { 63 | this.posts = posts; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/src/main/java/com/example/jpa/repository/PostRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.Post; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 22/11/17. 9 | */ 10 | @Repository 11 | public interface PostRepository extends JpaRepository { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/src/main/java/com/example/jpa/repository/TagRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.Tag; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 22/11/17. 9 | */ 10 | @Repository 11 | public interface TagRepository extends JpaRepository { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-many-to-many-demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) 2 | spring.datasource.url=jdbc:mysql://localhost:3306/jpa_many_to_many_demo?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false 3 | spring.datasource.username=root 4 | spring.datasource.password=callicoder 5 | 6 | # Hibernate 7 | 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 10 | 11 | # Hibernate ddl auto (create, create-drop, validate, update) 12 | spring.jpa.hibernate.ddl-auto = update 13 | 14 | logging.level.org.hibernate.SQL=DEBUG 15 | logging.level.org.hibernate.type=TRACE -------------------------------------------------------------------------------- /jpa-many-to-many-demo/src/test/java/com/example/jpa/JpaManyToManyDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class JpaManyToManyDemoApplicationTests { 8 | 9 | @Test 10 | public void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /jpa-one-to-many-demo/Readme.md: -------------------------------------------------------------------------------- 1 | # Hibernate One to Many Mapping Example with Spring Boot and JPA 2 | 3 | Read the Tutorial - https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/ 4 | 5 | ## Setup the Application 6 | 7 | 1. Create a database named `hibernate_one_to_many_demo`. 8 | 9 | 2. Open `src/main/resources/application.properties` and change `spring.datasource.username` and `spring.datasource.password` properties as per your MySQL installation. 10 | 11 | 3. Type `mvn spring-boot:run` from the root directory of the project to run the application. -------------------------------------------------------------------------------- /jpa-one-to-many-demo/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 | # http://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 | # Maven2 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 /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/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 http://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 Maven2 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 key stroke 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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | hibernate-one-to-many-demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | hibernate-one-to-many-demo 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.5.5 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 11 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-validation 39 | 40 | 41 | mysql 42 | mysql-connector-java 43 | runtime 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/JpaOneToManyDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 6 | 7 | @SpringBootApplication 8 | @EnableJpaAuditing 9 | public class JpaOneToManyDemoApplication { 10 | public static void main(String[] args) { 11 | SpringApplication.run(JpaOneToManyDemoApplication.class, args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/controller/CommentController.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.controller; 2 | 3 | import com.example.jpa.exception.ResourceNotFoundException; 4 | import com.example.jpa.model.Comment; 5 | import com.example.jpa.repository.CommentRepository; 6 | import com.example.jpa.repository.PostRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.Pageable; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import javax.validation.Valid; 14 | 15 | @RestController 16 | public class CommentController { 17 | 18 | @Autowired 19 | private CommentRepository commentRepository; 20 | 21 | @Autowired 22 | private PostRepository postRepository; 23 | 24 | @GetMapping("/posts/{postId}/comments") 25 | public Page getAllCommentsByPostId(@PathVariable (value = "postId") Long postId, 26 | Pageable pageable) { 27 | return commentRepository.findByPostId(postId, pageable); 28 | } 29 | 30 | @PostMapping("/posts/{postId}/comments") 31 | public Comment createComment(@PathVariable (value = "postId") Long postId, 32 | @Valid @RequestBody Comment comment) { 33 | return postRepository.findById(postId).map(post -> { 34 | comment.setPost(post); 35 | return commentRepository.save(comment); 36 | }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found")); 37 | } 38 | 39 | @PutMapping("/posts/{postId}/comments/{commentId}") 40 | public Comment updateComment(@PathVariable (value = "postId") Long postId, 41 | @PathVariable (value = "commentId") Long commentId, 42 | @Valid @RequestBody Comment commentRequest) { 43 | if(!postRepository.existsById(postId)) { 44 | throw new ResourceNotFoundException("PostId " + postId + " not found"); 45 | } 46 | 47 | return commentRepository.findById(commentId).map(comment -> { 48 | comment.setText(commentRequest.getText()); 49 | return commentRepository.save(comment); 50 | }).orElseThrow(() -> new ResourceNotFoundException("CommentId " + commentId + "not found")); 51 | } 52 | 53 | @DeleteMapping("/posts/{postId}/comments/{commentId}") 54 | public ResponseEntity deleteComment(@PathVariable (value = "postId") Long postId, 55 | @PathVariable (value = "commentId") Long commentId) { 56 | return commentRepository.findByIdAndPostId(commentId, postId).map(comment -> { 57 | commentRepository.delete(comment); 58 | return ResponseEntity.ok().build(); 59 | }).orElseThrow(() -> new ResourceNotFoundException("Comment not found with id " + commentId + " and postId " + postId)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/controller/PostController.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.controller; 2 | 3 | import com.example.jpa.exception.ResourceNotFoundException; 4 | import com.example.jpa.model.Post; 5 | import com.example.jpa.repository.PostRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | import javax.validation.Valid; 13 | 14 | @RestController 15 | public class PostController { 16 | 17 | @Autowired 18 | private PostRepository postRepository; 19 | 20 | @GetMapping("/posts") 21 | public Page getAllPosts(Pageable pageable) { 22 | return postRepository.findAll(pageable); 23 | } 24 | 25 | @PostMapping("/posts") 26 | public Post createPost(@Valid @RequestBody Post post) { 27 | return postRepository.save(post); 28 | } 29 | 30 | @PutMapping("/posts/{postId}") 31 | public Post updatePost(@PathVariable Long postId, @Valid @RequestBody Post postRequest) { 32 | return postRepository.findById(postId).map(post -> { 33 | post.setTitle(postRequest.getTitle()); 34 | post.setDescription(postRequest.getDescription()); 35 | post.setContent(postRequest.getContent()); 36 | return postRepository.save(post); 37 | }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found")); 38 | } 39 | 40 | 41 | @DeleteMapping("/posts/{postId}") 42 | public ResponseEntity deletePost(@PathVariable Long postId) { 43 | return postRepository.findById(postId).map(post -> { 44 | postRepository.delete(post); 45 | return ResponseEntity.ok().build(); 46 | }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found")); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/exception/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(HttpStatus.NOT_FOUND) 7 | public class ResourceNotFoundException extends RuntimeException { 8 | public ResourceNotFoundException() { 9 | super(); 10 | } 11 | 12 | public ResourceNotFoundException(String message) { 13 | super(message); 14 | } 15 | 16 | public ResourceNotFoundException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/model/AuditModel.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import org.springframework.data.annotation.CreatedDate; 5 | import org.springframework.data.annotation.LastModifiedDate; 6 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 7 | 8 | import javax.persistence.*; 9 | import javax.validation.constraints.NotNull; 10 | import java.io.Serializable; 11 | import java.util.Date; 12 | 13 | @MappedSuperclass 14 | @EntityListeners(AuditingEntityListener.class) 15 | @JsonIgnoreProperties( 16 | value = {"createdAt", "updatedAt"}, 17 | allowGetters = true 18 | ) 19 | public abstract class AuditModel implements Serializable { 20 | @Temporal(TemporalType.TIMESTAMP) 21 | @Column(name = "created_at", nullable = false, updatable = false) 22 | @CreatedDate 23 | private Date createdAt; 24 | 25 | @Temporal(TemporalType.TIMESTAMP) 26 | @Column(name = "updated_at", nullable = false) 27 | @LastModifiedDate 28 | private Date updatedAt; 29 | 30 | public Date getCreatedAt() { 31 | return createdAt; 32 | } 33 | 34 | public void setCreatedAt(Date createdAt) { 35 | this.createdAt = createdAt; 36 | } 37 | 38 | public Date getUpdatedAt() { 39 | return updatedAt; 40 | } 41 | 42 | public void setUpdatedAt(Date updatedAt) { 43 | this.updatedAt = updatedAt; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/model/Comment.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import com.fasterxml.jackson.annotation.*; 4 | 5 | import javax.persistence.*; 6 | import javax.validation.constraints.NotNull; 7 | 8 | import org.hibernate.annotations.OnDelete; 9 | import org.hibernate.annotations.OnDeleteAction; 10 | 11 | /** 12 | * Created by rajeevkumarsingh on 21/11/17. 13 | */ 14 | @Entity 15 | @Table(name = "comments") 16 | public class Comment extends AuditModel { 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private Long id; 20 | 21 | @NotNull 22 | @Lob 23 | private String text; 24 | 25 | @ManyToOne(fetch = FetchType.LAZY, optional = false) 26 | @JoinColumn(name = "post_id", nullable = false) 27 | @OnDelete(action = OnDeleteAction.CASCADE) 28 | @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") 29 | @JsonIdentityReference(alwaysAsId=true) 30 | @JsonProperty("post_id") 31 | private Post post; 32 | 33 | public Long getId() { 34 | return id; 35 | } 36 | 37 | public void setId(Long id) { 38 | this.id = id; 39 | } 40 | 41 | public String getText() { 42 | return text; 43 | } 44 | 45 | public void setText(String text) { 46 | this.text = text; 47 | } 48 | 49 | public Post getPost() { 50 | return post; 51 | } 52 | 53 | public void setPost(Post post) { 54 | this.post = post; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/model/Post.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.*; 4 | import javax.validation.constraints.NotNull; 5 | import javax.validation.constraints.Size; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 21/11/17. 9 | */ 10 | @Entity 11 | @Table(name = "posts") 12 | public class Post extends AuditModel { 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.IDENTITY) 15 | private Long id; 16 | 17 | @NotNull 18 | @Size(max = 100) 19 | @Column(unique = true) 20 | private String title; 21 | 22 | @NotNull 23 | @Size(max = 250) 24 | private String description; 25 | 26 | @NotNull 27 | @Lob 28 | private String content; 29 | 30 | public Long getId() { 31 | return id; 32 | } 33 | 34 | public void setId(Long id) { 35 | this.id = id; 36 | } 37 | 38 | public String getTitle() { 39 | return title; 40 | } 41 | 42 | public void setTitle(String title) { 43 | this.title = title; 44 | } 45 | 46 | public String getDescription() { 47 | return description; 48 | } 49 | 50 | public void setDescription(String description) { 51 | this.description = description; 52 | } 53 | 54 | public String getContent() { 55 | return content; 56 | } 57 | 58 | public void setContent(String content) { 59 | this.content = content; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/repository/CommentRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.Comment; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.util.Optional; 10 | 11 | /** 12 | * Created by rajeevkumarsingh on 21/11/17. 13 | */ 14 | @Repository 15 | public interface CommentRepository extends JpaRepository { 16 | Page findByPostId(Long postId, Pageable pageable); 17 | Optional findByIdAndPostId(Long id, Long postId); 18 | } 19 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/java/com/example/jpa/repository/PostRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.Post; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 21/11/17. 9 | */ 10 | @Repository 11 | public interface PostRepository extends JpaRepository { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) 2 | spring.datasource.url=jdbc:mysql://localhost:3306/jpa_one_to_many_demo?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false 3 | spring.datasource.username=root 4 | spring.datasource.password=callicoder 5 | 6 | # Hibernate 7 | 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 10 | 11 | # Hibernate ddl auto (create, create-drop, validate, update) 12 | spring.jpa.hibernate.ddl-auto = update 13 | 14 | logging.level.org.hibernate.SQL=DEBUG 15 | logging.level.org.hibernate.type=TRACE -------------------------------------------------------------------------------- /jpa-one-to-many-demo/src/test/java/com/example/jpa/JpaOneToManyDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class JpaOneToManyDemoApplicationTests { 8 | 9 | @Test 10 | public void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /jpa-one-to-one-demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/callicoder/jpa-hibernate-tutorials/1cca1d2708eb9ed14989f61aa5ea02d4f0cb8268/jpa-one-to-one-demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /jpa-one-to-one-demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/Readme.md: -------------------------------------------------------------------------------- 1 | # Hibernate One to One Mapping Example with Spring Boot and JPA 2 | 3 | Read the Tutorial - https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-one-mapping-example/ 4 | 5 | ## Setup the Application 6 | 7 | 1. Create a database named `hibernate_one_to_one_demo`. 8 | 9 | 2. Open `src/main/resources/application.properties` and change `spring.datasource.username` and `spring.datasource.password` properties as per your MySQL installation. 10 | 11 | 3. Type `mvn spring-boot:run` from the root directory of the project to run the application. -------------------------------------------------------------------------------- /jpa-one-to-one-demo/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 | # http://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 | # Maven2 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 /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/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 http://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 Maven2 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 key stroke 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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | hibernate-one-to-one-demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | hibernate-one-to-one-demo 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.5.5 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 11 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-validation 39 | 40 | 41 | mysql 42 | mysql-connector-java 43 | runtime 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/src/main/java/com/example/jpa/JpaOneToOneDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import com.example.jpa.model.Gender; 4 | import com.example.jpa.model.User; 5 | import com.example.jpa.model.UserProfile; 6 | import com.example.jpa.repository.UserRepository; 7 | import com.example.jpa.repository.UserProfileRepository; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.CommandLineRunner; 10 | import org.springframework.boot.SpringApplication; 11 | import org.springframework.boot.autoconfigure.SpringBootApplication; 12 | import java.util.Calendar; 13 | 14 | @SpringBootApplication 15 | public class JpaOneToOneDemoApplication implements CommandLineRunner { 16 | 17 | @Autowired 18 | private UserRepository userRepository; 19 | 20 | @Autowired 21 | private UserProfileRepository userProfileRepository; 22 | 23 | public static void main(String[] args) { 24 | SpringApplication.run(JpaOneToOneDemoApplication.class, args); 25 | } 26 | 27 | @Override 28 | public void run(String... args) throws Exception { 29 | // Clean up database tables 30 | userProfileRepository.deleteAllInBatch(); 31 | userRepository.deleteAllInBatch(); 32 | 33 | //========================================= 34 | 35 | // Create a User instance 36 | User user = new User("Rajeev", "Singh", "rajeev@callicoder.com", 37 | "MY_SUPER_SECRET_PASSWORD"); 38 | 39 | Calendar dateOfBirth = Calendar.getInstance(); 40 | dateOfBirth.set(1992, 7, 21); 41 | 42 | // Create a UserProfile instance 43 | UserProfile userProfile = new UserProfile("+91-8197882053", Gender.MALE, dateOfBirth.getTime(), 44 | "747", "2nd Cross", "Golf View Road, Kodihalli", "Bangalore", 45 | "Karnataka", "India", "560008"); 46 | 47 | 48 | // Set child reference(userProfile) in parent entity(user) 49 | user.setUserProfile(userProfile); 50 | 51 | // Set parent reference(user) in child entity(userProfile) 52 | userProfile.setUser(user); 53 | 54 | // Save Parent Reference (which will save the child as well) 55 | userRepository.save(user); 56 | 57 | //========================================= 58 | } 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/src/main/java/com/example/jpa/model/Gender.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | /** 4 | * Created by rajeevkumarsingh on 29/11/17. 5 | */ 6 | public enum Gender { 7 | MALE, 8 | FEMALE 9 | } 10 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/src/main/java/com/example/jpa/model/User.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.*; 4 | import javax.validation.constraints.Email; 5 | import javax.validation.constraints.NotNull; 6 | import javax.validation.constraints.Size; 7 | import java.io.Serializable; 8 | 9 | /** 10 | * Created by rajeevkumarsingh on 20/11/17. 11 | */ 12 | @Entity 13 | @Table(name = "users") 14 | public class User implements Serializable { 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private Long id; 18 | 19 | @NotNull 20 | @Size(max = 65) 21 | @Column(name = "first_name") 22 | private String firstName; 23 | 24 | @Size(max = 65) 25 | @Column(name = "last_name") 26 | private String lastName; 27 | 28 | @NotNull 29 | @Email 30 | @Size(max = 100) 31 | @Column(unique = true) 32 | private String email; 33 | 34 | @NotNull 35 | @Size(max = 128) 36 | private String password; 37 | 38 | @OneToOne(fetch = FetchType.LAZY, 39 | cascade = CascadeType.ALL, 40 | mappedBy = "user") 41 | private UserProfile userProfile; 42 | 43 | // Hibernate requires a no-arg constructor 44 | public User() { 45 | 46 | } 47 | 48 | public User(String firstName, String lastName, String email, String password) { 49 | this.firstName = firstName; 50 | this.lastName = lastName; 51 | this.email = email; 52 | this.password = password; 53 | } 54 | 55 | public Long getId() { 56 | return id; 57 | } 58 | 59 | public void setId(Long id) { 60 | this.id = id; 61 | } 62 | 63 | public String getFirstName() { 64 | return firstName; 65 | } 66 | 67 | public void setFirstName(String firstName) { 68 | this.firstName = firstName; 69 | } 70 | 71 | public String getLastName() { 72 | return lastName; 73 | } 74 | 75 | public void setLastName(String lastName) { 76 | this.lastName = lastName; 77 | } 78 | 79 | public String getEmail() { 80 | return email; 81 | } 82 | 83 | public void setEmail(String email) { 84 | this.email = email; 85 | } 86 | 87 | public String getPassword() { 88 | return password; 89 | } 90 | 91 | public void setPassword(String password) { 92 | this.password = password; 93 | } 94 | 95 | 96 | public UserProfile getUserProfile() { 97 | return userProfile; 98 | } 99 | 100 | public void setUserProfile(UserProfile userProfile) { 101 | this.userProfile = userProfile; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/src/main/java/com/example/jpa/model/UserProfile.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.model; 2 | 3 | import javax.persistence.*; 4 | import javax.validation.constraints.Size; 5 | import java.io.Serializable; 6 | import java.util.Date; 7 | 8 | /** 9 | * Created by rajeevkumarsingh on 20/11/17. 10 | */ 11 | @Entity 12 | @Table(name = "user_profiles") 13 | public class UserProfile implements Serializable { 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private Long id; 17 | 18 | @Column(name = "phone_number") 19 | @Size(max = 15) 20 | private String phoneNumber; 21 | 22 | @Enumerated(EnumType.STRING) 23 | @Column(length = 10) 24 | private Gender gender; 25 | 26 | @Temporal(TemporalType.DATE) 27 | @Column(name = "dob") 28 | private Date dateOfBirth; 29 | 30 | @Size(max = 100) 31 | private String address1; 32 | 33 | @Size(max = 100) 34 | private String address2; 35 | 36 | @Size(max = 100) 37 | private String street; 38 | 39 | @Size(max = 100) 40 | private String city; 41 | 42 | @Size(max = 100) 43 | private String state; 44 | 45 | @Size(max = 100) 46 | private String country; 47 | 48 | @Column(name = "zip_code") 49 | @Size(max = 32) 50 | private String zipCode; 51 | 52 | @OneToOne(fetch = FetchType.LAZY, optional = false) 53 | @JoinColumn(name = "user_id", nullable = false) 54 | private User user; 55 | 56 | public UserProfile() { 57 | 58 | } 59 | 60 | public UserProfile(String phoneNumber, Gender gender, Date dateOfBirth, 61 | String address1, String address2, String street, String city, 62 | String state, String country, String zipCode) { 63 | this.phoneNumber = phoneNumber; 64 | this.gender = gender; 65 | this.dateOfBirth = dateOfBirth; 66 | this.address1 = address1; 67 | this.address2 = address2; 68 | this.street = street; 69 | this.city = city; 70 | this.state = state; 71 | this.country = country; 72 | this.zipCode = zipCode; 73 | } 74 | 75 | public Long getId() { 76 | return id; 77 | } 78 | 79 | public void setId(Long id) { 80 | this.id = id; 81 | } 82 | 83 | public String getPhoneNumber() { 84 | return phoneNumber; 85 | } 86 | 87 | public void setPhoneNumber(String phoneNumber) { 88 | this.phoneNumber = phoneNumber; 89 | } 90 | 91 | public Gender getGender() { 92 | return gender; 93 | } 94 | 95 | public void setGender(Gender gender) { 96 | this.gender = gender; 97 | } 98 | 99 | public Date getDateOfBirth() { 100 | return dateOfBirth; 101 | } 102 | 103 | public void setDateOfBirth(Date dateOfBirth) { 104 | this.dateOfBirth = dateOfBirth; 105 | } 106 | 107 | public String getAddress1() { 108 | return address1; 109 | } 110 | 111 | public void setAddress1(String address1) { 112 | this.address1 = address1; 113 | } 114 | 115 | public String getAddress2() { 116 | return address2; 117 | } 118 | 119 | public void setAddress2(String address2) { 120 | this.address2 = address2; 121 | } 122 | 123 | public String getStreet() { 124 | return street; 125 | } 126 | 127 | public void setStreet(String street) { 128 | this.street = street; 129 | } 130 | 131 | public String getCity() { 132 | return city; 133 | } 134 | 135 | public void setCity(String city) { 136 | this.city = city; 137 | } 138 | 139 | public String getState() { 140 | return state; 141 | } 142 | 143 | public void setState(String state) { 144 | this.state = state; 145 | } 146 | 147 | public String getCountry() { 148 | return country; 149 | } 150 | 151 | public void setCountry(String country) { 152 | this.country = country; 153 | } 154 | 155 | public String getZipCode() { 156 | return zipCode; 157 | } 158 | 159 | public void setZipCode(String zipCode) { 160 | this.zipCode = zipCode; 161 | } 162 | 163 | public User getUser() { 164 | return user; 165 | } 166 | 167 | public void setUser(User user) { 168 | this.user = user; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/src/main/java/com/example/jpa/repository/UserProfileRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.UserProfile; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 20/11/17. 9 | */ 10 | @Repository 11 | public interface UserProfileRepository extends JpaRepository { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/src/main/java/com/example/jpa/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa.repository; 2 | 3 | import com.example.jpa.model.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by rajeevkumarsingh on 20/11/17. 9 | */ 10 | @Repository 11 | public interface UserRepository extends JpaRepository { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /jpa-one-to-one-demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) 2 | spring.datasource.url=jdbc:mysql://localhost:3306/jpa_one_to_one_demo?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false 3 | spring.datasource.username=root 4 | spring.datasource.password=callicoder 5 | 6 | # Hibernate 7 | 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 10 | 11 | # Hibernate ddl auto (create, create-drop, validate, update) 12 | spring.jpa.hibernate.ddl-auto = update 13 | 14 | logging.level.org.hibernate.SQL=DEBUG 15 | logging.level.org.hibernate.type=TRACE -------------------------------------------------------------------------------- /jpa-one-to-one-demo/src/test/java/com/example/jpa/JpaOneToOneDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.jpa; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class JpaOneToOneDemoApplicationTests { 8 | 9 | @Test 10 | public void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------