├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── include ├── loda_checkStyle.xml ├── loda_codeStyle.xml └── loda_findBug.xml ├── java-reflection-annotations ├── readme.md └── src │ └── main │ └── java │ └── me │ └── loda │ └── java │ └── reflection │ ├── ClassExample.java │ ├── CreateClassExample.java │ ├── FieldExample.java │ ├── GetListMethod.java │ ├── Girl.java │ ├── ListAnnotationExample.java │ ├── MethodExample.java │ ├── Person.java │ ├── annotationadvanced │ ├── Convertible.java │ ├── CustomEnum.java │ ├── CustomEnumConverter.java │ └── EnumToIntegerConverter.java │ └── annotations │ ├── AnnotaionExample.java │ ├── JsonName.java │ ├── JsonNameProcessor.java │ └── SuperMan.java ├── java-security-jwt └── src │ └── main │ └── java │ └── me │ └── loda │ └── java │ └── security │ └── Main.java ├── java-thread-pool-executor ├── readme.md └── src │ └── main │ └── java │ └── me │ └── loda │ └── java │ └── threadpool │ ├── CachedThreadPoolExample.java │ ├── FixedThreadPoolExample.java │ ├── Main.java │ ├── RequestHandler.java │ └── SingleThreadPoolExample.java ├── java-threadpoolexecutor ├── readme.md └── src │ └── main │ └── java │ └── me │ └── loda │ └── threadpoolexecutor │ ├── RequestHandler.java │ └── ThreadPoolExecutorExample.java ├── jpa-hibernate-many-to-many ├── build.gradle ├── readme.md └── src │ └── main │ ├── java │ └── me │ │ └── loda │ │ └── jpa │ │ └── manytomany │ │ ├── Address.java │ │ ├── AddressRepository.java │ │ ├── ManyToManyExampleApplication.java │ │ ├── Person.java │ │ └── PersonRepository.java │ └── resources │ └── application.properties ├── jpa-hibernate-one-to-many ├── build.gradle ├── readme.md └── src │ └── main │ ├── java │ └── me │ │ └── loda │ │ └── jpa │ │ └── manytomany │ │ ├── Address.java │ │ ├── AddressRepository.java │ │ ├── OneToManyExampleApplication.java │ │ ├── Person.java │ │ └── PersonRepository.java │ └── resources │ └── application.properties ├── jpa-hibernate-one-to-one ├── build.gradle ├── readme.md └── src │ └── main │ ├── java │ └── me │ │ └── loda │ │ └── jpa │ │ └── manytomany │ │ ├── Address.java │ │ ├── AddressRepository.java │ │ ├── OneToOneExampleApplication.java │ │ ├── Person.java │ │ └── PersonRepository.java │ └── resources │ └── application.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | !gradle/wrapper/gradle-wrapper.jar 25 | **/build/ 26 | **/out/ 27 | .gradle 28 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Nguyen Hoang Nam 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # loda.me-java-all 2 | Hướng dẫn tất tần tật về Java 3 | 4 | Đang bổ sung readme.md và hướng dẫn cài đặt -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'checkstyle' 4 | } 5 | 6 | ext{ 7 | lombokVersion = '1.18.4' 8 | guavaVersion = '27.1-jre' 9 | commonLang3Version = '3.8.1' 10 | } 11 | 12 | allprojects { 13 | group 'me.loda.java' 14 | version '1.0-SNAPSHOT' 15 | 16 | apply plugin: 'java' 17 | apply plugin: 'idea' 18 | apply plugin: 'checkstyle' 19 | 20 | def defaultEncoding = 'UTF-8' 21 | tasks.withType(AbstractCompile).each { it.options.encoding = defaultEncoding } 22 | 23 | checkstyle { 24 | def configDir = new File(project.rootDir, "include") 25 | configFile = new File(configDir, "loda_checkStyle.xml") 26 | configProperties.configDir = configDir 27 | } 28 | 29 | sourceCompatibility = 1.8 30 | targetCompatibility = 1.8 31 | 32 | configurations { 33 | compileOnly { 34 | extendsFrom annotationProcessor 35 | } 36 | } 37 | 38 | repositories { 39 | mavenCentral() 40 | jcenter() 41 | } 42 | } 43 | 44 | 45 | subprojects { 46 | compileJava.dependsOn(processResources) 47 | 48 | dependencies { 49 | // Annotation processor 50 | annotationProcessor "org.projectlombok:lombok:${lombokVersion}" 51 | compileOnly "org.projectlombok:lombok:${lombokVersion}" 52 | 53 | 54 | // utils 55 | compile group: 'com.google.guava', name: 'guava', version: "${guavaVersion}" 56 | compile group: 'org.apache.commons', name: 'commons-lang3', version: "${commonLang3Version}" 57 | } 58 | } 59 | 60 | project(":java-reflection-annotations"){ 61 | dependencies { 62 | // https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api 63 | compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: '1.0.2.Final' 64 | compile 'com.google.guava:guava:27.1-jre' 65 | } 66 | } 67 | 68 | project(":jpa-hibernate-one-to-one"){} 69 | project(":jpa-hibernate-one-to-many"){} 70 | project(":jpa-hibernate-many-to-many"){} 71 | project(":java-thread-pool-executor"){} 72 | project(":java-threadpoolexecutor"){} 73 | 74 | gradle.buildFinished { 75 | project.buildDir.deleteDir() 76 | delete "src" 77 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loda-kun/java-all/7f14b3e32ee5fb9c3c222fb727f067458a0c0c39/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /include/loda_checkStyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /include/loda_codeStyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 28 | -------------------------------------------------------------------------------- /include/loda_findBug.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 | 762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 783 | 784 | 785 | 786 | 787 | 788 | 789 | 790 | 791 | 792 | 793 | 794 | 795 | 796 | 797 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 | 824 | 825 | 826 | 827 | 828 | 829 | 830 | 831 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 | 842 | 843 | 844 | 845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 | 853 | 854 | 855 | 856 | 857 | 858 | 859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 | 867 | 868 | 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 | 879 | 880 | 881 | 882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 | 896 | 897 | 898 | 899 | 900 | 901 | 902 | 903 | 904 | 905 | 906 | 907 | 908 | 909 | 910 | 911 | 912 | 913 | 914 | 915 | 916 | 917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | 925 | 926 | 927 | 928 | 929 | 930 | 931 | 932 | 933 | 934 | 935 | 936 | 937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 | 951 | 952 | 953 | 954 | 955 | 956 | 957 | 958 | 959 | 960 | 961 | 962 | 963 | 964 | 965 | 966 | 967 | 968 | 969 | 970 | 971 | 972 | 973 | 974 | 975 | 976 | 977 | 978 | 979 | 980 | 981 | 982 | 983 | 984 | 985 | 986 | 987 | 988 | 989 | 990 | 991 | 992 | 993 | 994 | 995 | 996 | 997 | 998 | 999 | 1000 | 1001 | 1002 | 1003 | 1004 | 1005 | 1006 | 1007 | 1008 | 1009 | 1010 | 1011 | 1012 | 1013 | 1014 | 1015 | 1016 | 1017 | 1018 | 1019 | 1020 | 1021 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 | 1033 | 1034 | 1035 | 1036 | 1037 | 1038 | 1039 | 1040 | 1041 | 1042 | 1043 | 1044 | 1045 | 1046 | 1047 | 1048 | 1049 | 1050 | 1051 | 1052 | 1053 | 1054 | 1055 | 1056 | 1057 | -------------------------------------------------------------------------------- /java-reflection-annotations/readme.md: -------------------------------------------------------------------------------- 1 | # Hướng dẫn Java Reflection 2 | [https://loda.me/Huong-dan-Java-Reflection/](https://loda.me/Huong-dan-Java-Reflection/) 3 | 4 | # Hướng dẫn tự tạo Annotation 5 | [https://loda.me/Huong-dan-tu-tao-mot-Annotations/](https://loda.me/Huong-dan-tu-tao-mot-Annotations/) 6 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/ClassExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Constructor; 5 | import java.lang.reflect.Field; 6 | import java.lang.reflect.Method; 7 | import java.lang.reflect.Modifier; 8 | 9 | public class ClassExample { 10 | 11 | public static void main(String[] args) throws ClassNotFoundException { 12 | getClassInfo(); 13 | } 14 | public static void getClassInfo() throws ClassNotFoundException { 15 | Class aClazz = Girl.class; 16 | System.out.println("Name: " + aClazz.getName()); 17 | System.out.println("Simple Name: " + aClazz.getSimpleName()); 18 | 19 | Package pkg = aClazz.getPackage(); 20 | System.out.println("Package Name = " + pkg.getName()); 21 | 22 | // Modifier 23 | int modifiers = aClazz.getModifiers(); 24 | boolean isPublic = Modifier.isPublic(modifiers); 25 | boolean isInterface = Modifier.isInterface(modifiers); 26 | boolean isAbstract = Modifier.isAbstract(modifiers); 27 | boolean isFinal = Modifier.isFinal(modifiers); 28 | 29 | System.out.println("Is Public? " + isPublic); // true 30 | System.out.println("Is Final? " + isFinal); // false 31 | System.out.println("Is Interface? " + isInterface); // false 32 | System.out.println("Is Abstract? " + isAbstract); // false 33 | 34 | // Lấy ra đối tượng class mô tả class cha của class Girl. 35 | Class aSuperClass = aClazz.getSuperclass(); 36 | System.out.println("Simple Class Name of Super class = " + aSuperClass.getSimpleName()); 37 | 38 | // Lấy ra mảng các Class mô tả các Interface mà Girl thi hành 39 | System.out.println("\nInterface:"); 40 | Class[] itfClasses = aClazz.getInterfaces(); 41 | for (Class itfClass : itfClasses) { 42 | System.out.println("+ " + itfClass.getSimpleName()); 43 | } 44 | 45 | // Lấy ra danh sách các cấu tử của Girl. 46 | System.out.println("\nConstructor:"); 47 | Constructor[] constructors = aClazz.getConstructors(); 48 | for (Constructor constructor : constructors) { 49 | System.out.println("+ " + constructor.getName() + " has " + constructor.getParameterCount() + " param"); 50 | } 51 | 52 | // Lấy ra danh sách các method public của Girl 53 | System.out.println("\nMethods:"); 54 | Method[] methods = aClazz.getMethods(); 55 | for (Method method : methods) { 56 | System.out.println("+ " + method.getName()); 57 | } 58 | 59 | // Lấy ra danh sách các method của Girl 60 | // Bao gồm cả các private method thừa kế từ class cha và các interface 61 | System.out.println("\nDeclaredMethods:"); 62 | Method[] dmethods = aClazz.getDeclaredMethods(); 63 | for (Method method : dmethods) { 64 | System.out.println("+ " + method.getName()); 65 | } 66 | 67 | // Lấy ra danh sách các field public 68 | // Kể các các public field thừa kế từ các class cha, và các interface 69 | System.out.println("\nField:"); 70 | Field[] fields = aClazz.getFields(); 71 | for (Field field : fields) { 72 | System.out.println("+ " + field.getName()); 73 | } 74 | 75 | // Lấy ra danh sách các Annotation của class. 76 | System.out.println("\nAnnotation:"); 77 | Annotation[] annotations = aClazz.getAnnotations(); 78 | for (Annotation ann : annotations) { 79 | System.out.println("+ " + ann.annotationType().getSimpleName()); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/CreateClassExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.util.Arrays; 5 | 6 | public class CreateClassExample { 7 | public static void main(String[] args) { 8 | Class girlClass = Girl.class; 9 | System.out.println("class: " + girlClass.getSimpleName()); 10 | System.out.println("Constructors: " + Arrays.toString(girlClass.getConstructors())); 11 | try { 12 | // Tạo ra một object Girl từ class. (Khởi tạo không tham số) 13 | Girl girl1 = girlClass.newInstance(); 14 | System.out.println("Girl1: " + girl1); 15 | 16 | // Lấy ra hàm constructor với tham số là 1 string -> public Girl(String name) {} 17 | Constructor girlConstructor = girlClass.getConstructor(String.class); 18 | Girl girl2 = girlConstructor.newInstance("Hello"); 19 | 20 | System.out.println("Girl2: " + girl2); 21 | } catch (Exception e) { 22 | // Exception xay ra khi constructor khong ton tai hoac tham so truyen vao khong dung 23 | e.printStackTrace(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/FieldExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | public class FieldExample { 6 | public static void main(String[] args) throws Exception { 7 | Girl girl = new Girl(); 8 | girl.setName("Ngoc trinh"); 9 | 10 | // Lay ra tat ca field cua object 11 | for(Field field : girl.getClass().getDeclaredFields()){ 12 | System.out.println(); 13 | System.out.println("Field: " +field.getName()); 14 | System.out.println("Type: " +field.getType()); 15 | } 16 | 17 | Field nameField = girl.getClass().getDeclaredField("name"); 18 | nameField.setAccessible(true); // Cho phep truy cap vao field private 19 | nameField.set(girl, "Bella"); // Doi gia tri cua name trong object girl 20 | 21 | System.out.println(girl); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/GetListMethod.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection; 2 | 3 | import java.lang.reflect.Method; 4 | import java.lang.reflect.Modifier; 5 | import java.util.Arrays; 6 | 7 | public class GetListMethod { 8 | 9 | public @interface ReadOnly{ 10 | 11 | } 12 | 13 | @ReadOnly 14 | public static int publicStaticMethod(int a) { 15 | return 0; 16 | } 17 | 18 | private static void privateStaticMethod(String b, Long c) { 19 | 20 | } 21 | 22 | public static void main(String[] args) { 23 | Method[] methods = GetListMethod.class.getDeclaredMethods(); 24 | for(Method method: methods){ 25 | System.out.println("===================================="); 26 | System.out.println("toGenericString(): " + method.toGenericString()); 27 | System.out.println("getName(): "+ method.getName()); 28 | System.out.println("getModifiers(): " + Modifier.toString(method.getModifiers())); 29 | System.out.println("getParameters(): " + Arrays.toString(method.getParameters())); 30 | System.out.println("getTypeParameters(): " + Arrays.toString(method.getTypeParameters())); 31 | System.out.println("getAnnotatedReturnType(): " + method.getAnnotatedReturnType().getType()); // trả về type của giá trị trả về 32 | System.out.println("getDeclaringClass(): " + method.getDeclaringClass()); 33 | System.out.println("getDefaultValue(): " + method.getDefaultValue()); 34 | System.out.println("===================================="); 35 | 36 | } 37 | } 38 | 39 | // Protected method 40 | protected void protectedMethod(T hello) { 41 | 42 | } 43 | 44 | private void privateMethod() { 45 | 46 | } 47 | 48 | public void publicMethod() { 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/Girl.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection; 2 | 3 | import javax.annotation.Nullable; 4 | 5 | @SuppressWarnings("deprecation") 6 | @Deprecated 7 | public class Girl extends Person { 8 | 9 | private String name; 10 | 11 | public Girl() { 12 | 13 | } 14 | 15 | public Girl(String name) { 16 | this.name = name; 17 | } 18 | 19 | @Nullable 20 | public void setName(String name){ 21 | this.name = name; 22 | } 23 | 24 | @Override 25 | public int getOutfit() { 26 | return NAKED; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return "Girl{" + 32 | "name='" + name + '\'' + 33 | '}'; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/ListAnnotationExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import java.lang.annotation.Annotation; 12 | import java.lang.reflect.Method; 13 | 14 | import org.checkerframework.checker.units.qual.A; 15 | 16 | /** 17 | * Copyright 2019 {@author Loda} (https://loda.me). 18 | * This project is licensed under the MIT license. 19 | * 20 | * @since 4/3/2019 21 | * Github: https://github.com/loda-kun 22 | */ 23 | public class ListAnnotationExample { 24 | public static void main(String[] args) { 25 | Class girlClass = Girl.class; 26 | System.out.println("Class: "+girlClass.getSimpleName()); // Lấy ra tên Class 27 | for(Annotation annotation : girlClass.getDeclaredAnnotations()){ 28 | System.out.println("Annotation: " + annotation.annotationType()); // Lấy ra tên các Annatation trên class này 29 | } 30 | 31 | for(Method method: girlClass.getDeclaredMethods()){ 32 | System.out.println("\nMethod: " + method.getName()); 33 | for(Annotation annotation : method.getAnnotations()){ 34 | System.out.println("Annotation: " + annotation.annotationType()); // Lấy ra tên các Annatation trên class này 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/MethodExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class MethodExample { 8 | public static void main(String[] args) throws Exception { 9 | Class girlClass = Girl.class; 10 | 11 | // Su dung getDeclaredMethods de lay ra nhung method cua class va cha no tu dinh nghia thoi. 12 | Method[] methods = girlClass.getDeclaredMethods(); 13 | for(Method method : methods){ 14 | System.out.println(); 15 | System.out.println("Method: " + method.getName()); 16 | System.out.println("Parameters: " + Arrays.toString(method.getParameters())); 17 | } 18 | 19 | // Lay ra method ten la setName va co 1 tham so truyen vao -> setName(String name) 20 | Method methodSetName = girlClass.getMethod("setName", String.class); 21 | 22 | // Thuc hien ham setName, tren object girl 23 | Girl girl = new Girl(); 24 | methodSetName.invoke(girl, "Ngoc Trinh"); 25 | System.out.println(girl); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/Person.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection; 2 | 3 | public abstract class Person { 4 | public static final int NAKED = 0; 5 | public static final int BIKINI = 0; 6 | public String getLocation() { 7 | return "Earth"; 8 | } 9 | 10 | public abstract int getOutfit(); 11 | } 12 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/annotationadvanced/Convertible.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection.annotationadvanced; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target(ElementType.TYPE) 10 | public @interface Convertible { 11 | 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @Target(ElementType.FIELD) 14 | @interface Value{ 15 | 16 | } 17 | 18 | @Retention(RetentionPolicy.RUNTIME) 19 | @Target(ElementType.METHOD) 20 | @interface Parser{ 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/annotationadvanced/CustomEnum.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection.annotationadvanced; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | 6 | @Convertible 7 | @AllArgsConstructor 8 | @Getter 9 | public enum CustomEnum { 10 | HELLO(1), 11 | HAHA(2); 12 | 13 | @Convertible.Value 14 | private int value; 15 | 16 | 17 | @Convertible.Parser 18 | public static CustomEnum of(Integer value){ 19 | switch (value){ 20 | case 1: return HELLO; 21 | case 2: return HAHA; 22 | default: return null; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/annotationadvanced/CustomEnumConverter.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection.annotationadvanced; 2 | 3 | import javax.persistence.AttributeConverter; 4 | import javax.persistence.Converter; 5 | 6 | @Converter 7 | public class CustomEnumConverter extends EnumToIntegerConverter { 8 | } 9 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/annotationadvanced/EnumToIntegerConverter.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection.annotationadvanced; 2 | 3 | import java.lang.reflect.Field; 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.lang.reflect.Method; 6 | import java.lang.reflect.Type; 7 | import java.util.stream.Stream; 8 | 9 | import javax.persistence.AttributeConverter; 10 | 11 | import com.google.common.reflect.TypeToken; 12 | 13 | import me.loda.java.reflection.annotationadvanced.Convertible.Parser; 14 | import me.loda.java.reflection.annotationadvanced.Convertible.Value; 15 | 16 | public class EnumToIntegerConverter implements AttributeConverter { 17 | private final TypeToken typeToken = new TypeToken(getClass()) { }; 18 | private final Class clazz = typeToken.getRawType(); // or getRawType() to return Class 19 | 20 | @Override 21 | public Integer convertToDatabaseColumn(T attribute) { 22 | Convertible convertible = clazz.getDeclaredAnnotation(Convertible.class); 23 | if (convertible == null) { 24 | throw new RuntimeException("Enum is not convertible!"); 25 | } 26 | Field field = Stream.of(clazz.getDeclaredFields()) 27 | .filter(f -> { 28 | f.setAccessible(true); 29 | return f.getAnnotation(Value.class) != null; 30 | }) 31 | .findFirst() 32 | .orElseThrow(() -> new RuntimeException("Enum is not convertible!")); 33 | Integer integer; 34 | try { 35 | integer = (Integer) field.get(attribute); 36 | } catch (IllegalAccessException e) { 37 | throw new RuntimeException(e); 38 | } 39 | return integer; 40 | } 41 | 42 | @Override 43 | public T convertToEntityAttribute(Integer dbData) { 44 | Convertible convertible = clazz.getDeclaredAnnotation(Convertible.class); 45 | if (convertible == null) { 46 | throw new RuntimeException("Enum is not convertible!"); 47 | } 48 | Method method = Stream.of(clazz.getDeclaredMethods()) 49 | .filter(m -> m.getAnnotation(Parser.class) != null) 50 | .findFirst() 51 | .orElseThrow(() -> new RuntimeException("Enum is not convertible!")); 52 | 53 | try { 54 | return (T) method.invoke(null, dbData); 55 | } catch (IllegalAccessException e) { 56 | e.printStackTrace(); 57 | } catch (InvocationTargetException e) { 58 | e.printStackTrace(); 59 | } 60 | return null; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/annotations/AnnotaionExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection.annotations; 2 | 3 | import java.lang.reflect.Field; 4 | import java.time.LocalDateTime; 5 | import java.util.Optional; 6 | 7 | public class AnnotaionExample { 8 | public static void main(String[] args) throws IllegalAccessException { 9 | SuperMan superMan = new SuperMan(); // Tao doi tuong super man 10 | superMan.setDateOfBirth(LocalDateTime.now()); 11 | superMan.setName("loda"); 12 | 13 | String json =JsonNameProcessor.toJson(superMan); 14 | System.out.println(json); 15 | } 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/annotations/JsonName.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection.annotations; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) 10 | public @interface JsonName { 11 | // Cung cấp tên dưới dạng Json 12 | String value(); 13 | } 14 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/annotations/JsonNameProcessor.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection.annotations; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import java.lang.reflect.Field; 12 | import java.util.Optional; 13 | 14 | /** 15 | * Copyright 2019 {@author Loda} (https://loda.me). 16 | * This project is licensed under the MIT license. 17 | * 18 | * @since 4/3/2019 19 | * Github: https://github.com/loda-kun 20 | */ 21 | public class JsonNameProcessor { 22 | public static String toJson(Object object) throws IllegalAccessException { 23 | StringBuilder sb = new StringBuilder(); // Sung string builder de tao json tu class 24 | 25 | Class clazz = object.getClass(); 26 | JsonName jsonClassName = clazz.getDeclaredAnnotation(JsonName.class); // Lay ra annotation tren Class Superman 27 | 28 | sb.append("{\n") 29 | .append("\t\"") 30 | // Lay gia tri cua Annotation, neu annotation la null thi lay ten Class thay the 31 | .append(Optional.ofNullable(jsonClassName).map(JsonName::value).orElse(clazz.getSimpleName())) 32 | .append("\": {\n"); // 33 | 34 | 35 | Field fields[] = clazz.getDeclaredFields(); 36 | for (int i = 0; i < fields.length; i++) { 37 | fields[i].setAccessible(true); // Set setAccessible = true. De co the truy cap vao field la private 38 | JsonName jsonFieldName = fields[i].getDeclaredAnnotation(JsonName.class); // get annotation tren field 39 | sb.append("\t\t\"") 40 | // Lay gia tri cua Annotation, neu annotation la null thi lay ten field thay the 41 | .append(Optional.ofNullable(jsonFieldName).map(JsonName::value).orElse(fields[i].getName())) // L 42 | .append("\": ") 43 | // Neu field la String hoac Object. thi append dau ngoac kep vao 44 | .append(fields[i].getType() == String.class || !fields[i].getType().isPrimitive() ? "\"" : "") 45 | // Lay gia tri cua field 46 | .append(fields[i].get(object)) 47 | // Neu field la String hoac Object. thi append dau ngoac kep vao 48 | .append(fields[i].getType() == String.class || !fields[i].getType().isPrimitive()? "\"" : "") 49 | .append(i != fields.length -1 ? ",\n" : "\n"); 50 | } 51 | sb.append("\t}\n"); 52 | sb.append("}"); 53 | 54 | return sb.toString(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /java-reflection-annotations/src/main/java/me/loda/java/reflection/annotations/SuperMan.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.reflection.annotations; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | import me.loda.java.reflection.Person; 6 | 7 | @JsonName(value = "super_man") 8 | public class SuperMan extends Person { 9 | private String name; 10 | 11 | @JsonName("date_of_birth") 12 | private LocalDateTime dateOfBirth; 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public LocalDateTime getDateOfBirth() { 23 | return dateOfBirth; 24 | } 25 | 26 | public void setDateOfBirth(LocalDateTime dateOfBirth) { 27 | this.dateOfBirth = dateOfBirth; 28 | } 29 | 30 | @Override 31 | public int getOutfit() { 32 | return NAKED; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /java-security-jwt/src/main/java/me/loda/java/security/Main.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.security; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.security.InvalidAlgorithmParameterException; 5 | import java.security.InvalidKeyException; 6 | import java.security.NoSuchAlgorithmException; 7 | import java.security.SecureRandom; 8 | import java.util.Base64; 9 | 10 | import javax.crypto.BadPaddingException; 11 | import javax.crypto.Cipher; 12 | import javax.crypto.IllegalBlockSizeException; 13 | import javax.crypto.KeyGenerator; 14 | import javax.crypto.NoSuchPaddingException; 15 | import javax.crypto.SecretKey; 16 | import javax.crypto.spec.GCMParameterSpec; 17 | 18 | public class Main { 19 | public final static SecureRandom secureRandom = new SecureRandom(); 20 | 21 | public static void main(String[] args) throws Exception, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { 22 | // Initialise random and generate key 23 | SecureRandom random = SecureRandom.getInstanceStrong(); 24 | KeyGenerator keyGen = KeyGenerator.getInstance("AES"); 25 | keyGen.init(128, random); 26 | SecretKey key = keyGen.generateKey(); 27 | 28 | String needToEncyptString = "needToEncString"; 29 | 30 | // Encrypt 31 | Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); 32 | byte[] nonce = generateNonce(12); //NEVER REUSE THIS NONCE WITH SAME KEY 33 | c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce)); 34 | byte[] encValue = c.doFinal(needToEncyptString.getBytes()); 35 | String encrypted = Base64.getUrlEncoder().encodeToString(formatCipherMsg(nonce, encValue)); 36 | byte[] decodedMsg = Base64.getUrlDecoder().decode(encrypted); 37 | 38 | // decrypt 39 | ByteBuffer byteBuffer = ByteBuffer.wrap(decodedMsg); 40 | int ivLength = byteBuffer.getInt(); 41 | if (ivLength != 12) { // check input parameter 42 | throw new IllegalArgumentException("invalid iv length"); 43 | } 44 | byte[] nonce1 = new byte[ivLength]; 45 | byteBuffer.get(nonce1); 46 | byte[] encValue1 = new byte[byteBuffer.remaining()]; 47 | byteBuffer.get(encValue1); 48 | c.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, nonce)); 49 | byte[] decValue = c.doFinal(encValue); 50 | String decryptedString = new String(decValue); 51 | System.out.println(needToEncyptString); 52 | System.out.println(decryptedString); 53 | } 54 | 55 | private static byte[] generateNonce(int nonceLength) { 56 | byte[] nonce = new byte[nonceLength]; 57 | secureRandom.nextBytes(nonce); //NEVER REUSE THIS NONCE WITH SAME KEY 58 | return nonce; 59 | } 60 | 61 | private static byte[] formatCipherMsg(byte[] iv, byte[] encValue) { 62 | ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.BYTES + iv.length + encValue.length); 63 | byteBuffer.putInt(iv.length); 64 | byteBuffer.put(iv); 65 | byteBuffer.put(encValue); 66 | return byteBuffer.array(); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /java-thread-pool-executor/readme.md: -------------------------------------------------------------------------------- 1 | #Khái niệm ThreadPool và Executor trong Java 2 | [https://loda.me/Khai-niem-ThreadPool-va-Executor-trong-Java/](https://loda.me/Khai-niem-ThreadPool-va-Executor-trong-Java/) -------------------------------------------------------------------------------- /java-thread-pool-executor/src/main/java/me/loda/java/threadpool/CachedThreadPoolExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.threadpool; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class CachedThreadPoolExample { 7 | public static void main(String[] args) throws InterruptedException { 8 | ExecutorService executor = Executors.newCachedThreadPool(); 9 | 10 | // Có 100 request tới cùng lúc 11 | 12 | for (int i = 0; i < 100; i++) { 13 | executor.execute(new RequestHandler("request-" + i)); 14 | Thread.sleep(200); 15 | } 16 | executor.shutdown(); // Không cho threadpool nhận thêm nhiệm vụ nào nữa 17 | 18 | 19 | while (!executor.isTerminated()) { 20 | // Chờ xử lý hết các request còn chờ trong Queue ... 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java-thread-pool-executor/src/main/java/me/loda/java/threadpool/FixedThreadPoolExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.threadpool; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import java.util.concurrent.ExecutorService; 12 | import java.util.concurrent.Executors; 13 | 14 | /** 15 | * Copyright 2019 {@author Loda} (https://loda.me). 16 | * This project is licensed under the MIT license. 17 | * 18 | * @since 4/9/2019 19 | * Github: https://github.com/loda-kun 20 | */ 21 | public class FixedThreadPoolExample { 22 | public static void main(String[] args) throws InterruptedException { 23 | ExecutorService executor = Executors.newFixedThreadPool(5); 24 | 25 | // Có 100 request tới cùng lúc 26 | 27 | for (int i = 0; i < 100; i++) { 28 | executor.execute(new RequestHandler("request-" + i)); 29 | } 30 | executor.shutdown(); // Không cho threadpool nhận thêm nhiệm vụ nào nữa 31 | 32 | while (!executor.isTerminated()) { 33 | // Chờ xử lý hết các request còn chờ trong Queue ... 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /java-thread-pool-executor/src/main/java/me/loda/java/threadpool/Main.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.threadpool; 2 | 3 | public class Main { 4 | } 5 | -------------------------------------------------------------------------------- /java-thread-pool-executor/src/main/java/me/loda/java/threadpool/RequestHandler.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.threadpool; 2 | 3 | public class RequestHandler implements Runnable { 4 | String name; 5 | public RequestHandler(String name){ 6 | this.name = name; 7 | } 8 | 9 | @Override 10 | public void run() { 11 | try { 12 | System.out.println(Thread.currentThread().getName() + " Starting process " + name); 13 | Thread.sleep(500); 14 | System.out.println(Thread.currentThread().getName() + " Finished process " + name); 15 | } catch (InterruptedException e) { 16 | e.printStackTrace(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java-thread-pool-executor/src/main/java/me/loda/java/threadpool/SingleThreadPoolExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.java.threadpool; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class SingleThreadPoolExample { 7 | public static void main(String[] args) { 8 | ExecutorService executor = Executors.newSingleThreadExecutor(); 9 | 10 | // Có 100 request tới cùng lúc 11 | 12 | for (int i = 0; i < 100; i++) { 13 | executor.execute(new RequestHandler("request-" + i)); 14 | } 15 | executor.shutdown(); // Không cho threadpool nhận thêm nhiệm vụ nào nữa 16 | 17 | 18 | while (!executor.isTerminated()) { 19 | // Chờ xử lý hết các request còn chờ trong Queue ... 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java-threadpoolexecutor/readme.md: -------------------------------------------------------------------------------- 1 | # ThreadPoolExecutor và nguyên tắc quản lý pool size 2 | [https://loda.me/ThreadPoolExecutor-va-nguyen-tac-quan-ly-pool-size/](https://loda.me/ThreadPoolExecutor-va-nguyen-tac-quan-ly-pool-size/) -------------------------------------------------------------------------------- /java-threadpoolexecutor/src/main/java/me/loda/threadpoolexecutor/RequestHandler.java: -------------------------------------------------------------------------------- 1 | package me.loda.threadpoolexecutor; 2 | 3 | public class RequestHandler implements Runnable { 4 | String name; 5 | public RequestHandler(String name){ 6 | this.name = name; 7 | } 8 | 9 | @Override 10 | public void run() { 11 | try { 12 | System.out.println(Thread.currentThread().getName() + " Starting process " + name); 13 | Thread.sleep(500); 14 | System.out.println(Thread.currentThread().getName() + " Finished process " + name); 15 | } catch (InterruptedException e) { 16 | e.printStackTrace(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java-threadpoolexecutor/src/main/java/me/loda/threadpoolexecutor/ThreadPoolExecutorExample.java: -------------------------------------------------------------------------------- 1 | package me.loda.threadpoolexecutor; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import java.util.concurrent.ArrayBlockingQueue; 12 | import java.util.concurrent.ThreadPoolExecutor; 13 | import java.util.concurrent.TimeUnit; 14 | 15 | /** 16 | * Copyright 2019 {@author Loda} (https://loda.me). 17 | * This project is licensed under the MIT license. 18 | * 19 | * @since 4/9/2019 20 | * Github: https://github.com/loda-kun 21 | */ 22 | public class ThreadPoolExecutorExample { 23 | public static void main(String[] args) throws InterruptedException { 24 | int corePoolSize = 5; 25 | int maximumPoolSize = 10; 26 | int queueCapacity = 100; 27 | ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, // Số corePoolSize 28 | maximumPoolSize, // số maximumPoolSize 29 | 10, // thời gian một thread được sống nếu không làm gì 30 | TimeUnit.SECONDS, 31 | new ArrayBlockingQueue<>(queueCapacity)); // Blocking queue để cho request đợi 32 | // 1000 request đến dồn dập, liền 1 phát, không nghỉ 33 | for (int i = 0; i < 1000; i++) { 34 | executor.execute(new RequestHandler("request-" + i)); 35 | Thread.sleep(50); 36 | } 37 | // executor.shutdown(); // Không cho threadpool nhận thêm nhiệm vụ nào nữa 38 | 39 | while (!executor.isTerminated()) { 40 | // Chờ xử lý hết các request còn chờ trong Queue ... 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /jpa-hibernate-many-to-many/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.4.RELEASE' 3 | id 'java' 4 | } 5 | apply plugin: 'io.spring.dependency-management' 6 | 7 | group 'me.loda.java' 8 | version '1.0-SNAPSHOT' 9 | 10 | sourceCompatibility = 1.8 11 | 12 | configurations { 13 | compileOnly { 14 | extendsFrom annotationProcessor 15 | } 16 | } 17 | 18 | repositories { 19 | mavenCentral() 20 | } 21 | 22 | dependencies { 23 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 24 | implementation 'org.springframework.boot:spring-boot-starter-web' 25 | compileOnly 'org.projectlombok:lombok' 26 | runtimeOnly 'com.h2database:h2' 27 | annotationProcessor 'org.projectlombok:lombok' 28 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 29 | } 30 | -------------------------------------------------------------------------------- /jpa-hibernate-many-to-many/readme.md: -------------------------------------------------------------------------------- 1 | # Hướng dẫn @ManyToMany 2 | [https://loda.me/Huong-dan-@ManyToMany/](https://loda.me/Huong-dan-@ManyToMany/) -------------------------------------------------------------------------------- /jpa-hibernate-many-to-many/src/main/java/me/loda/jpa/manytomany/Address.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import java.util.Collection; 12 | 13 | import javax.persistence.CascadeType; 14 | import javax.persistence.Entity; 15 | import javax.persistence.FetchType; 16 | import javax.persistence.GeneratedValue; 17 | import javax.persistence.Id; 18 | import javax.persistence.JoinColumn; 19 | import javax.persistence.JoinTable; 20 | import javax.persistence.ManyToMany; 21 | 22 | import lombok.AllArgsConstructor; 23 | import lombok.Builder; 24 | import lombok.Data; 25 | import lombok.EqualsAndHashCode; 26 | import lombok.NoArgsConstructor; 27 | import lombok.ToString; 28 | 29 | /** 30 | * Copyright 2019 {@author Loda} (https://loda.me). 31 | * This project is licensed under the MIT license. 32 | * 33 | * @since 4/5/2019 34 | * Github: https://github.com/loda-kun 35 | */ 36 | @Entity // Đánh dấu đây là table trong db 37 | @Data // lombok giúp generate các hàm constructor, get, set v.v. 38 | @AllArgsConstructor 39 | @NoArgsConstructor 40 | @Builder 41 | public class Address { 42 | 43 | @Id //Đánh dấu là primary key 44 | @GeneratedValue // Giúp tự động tăng 45 | private Long id; 46 | 47 | private String city; 48 | private String province; 49 | 50 | @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) 51 | // Quan hệ n-n với đối tượng ở dưới (Person) (1 địa điểm có nhiều người ở) 52 | @EqualsAndHashCode.Exclude // không sử dụng trường này trong equals và hashcode 53 | @ToString.Exclude // Khoonhg sử dụng trong toString() 54 | 55 | @JoinTable(name = "address_person", //Tạo ra một join Table tên là "address_person" 56 | joinColumns = @JoinColumn(name = "address_id"), // TRong đó, khóa ngoại chính là address_id trỏ tới class hiện tại (Address) 57 | inverseJoinColumns = @JoinColumn(name = "person_id") //Khóa ngoại thứ 2 trỏ tới thuộc tính ở dưới (Person) 58 | ) 59 | private Collection persons; 60 | } 61 | -------------------------------------------------------------------------------- /jpa-hibernate-many-to-many/src/main/java/me/loda/jpa/manytomany/AddressRepository.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import org.springframework.data.jpa.repository.JpaRepository; 12 | 13 | /** 14 | * Copyright 2019 {@author Loda} (https://loda.me). 15 | * This project is licensed under the MIT license. 16 | * 17 | * @since 4/5/2019 18 | * Github: https://github.com/loda-kun 19 | */ 20 | // Kế thừa JpaRepository để giao tiếp với database 21 | public interface AddressRepository extends JpaRepository { 22 | } 23 | -------------------------------------------------------------------------------- /jpa-hibernate-many-to-many/src/main/java/me/loda/jpa/manytomany/ManyToManyExampleApplication.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | 12 | import javax.transaction.Transactional; 13 | 14 | import org.springframework.boot.CommandLineRunner; 15 | import org.springframework.boot.SpringApplication; 16 | import org.springframework.boot.autoconfigure.SpringBootApplication; 17 | 18 | import com.google.common.collect.Lists; 19 | 20 | import lombok.RequiredArgsConstructor; 21 | 22 | /** 23 | * Copyright 2019 {@author Loda} (https://loda.me). 24 | * This project is licensed under the MIT license. 25 | * 26 | * @since 4/5/2019 27 | * Github: https://github.com/loda-kun 28 | */ 29 | @SpringBootApplication 30 | @RequiredArgsConstructor 31 | public class ManyToManyExampleApplication implements CommandLineRunner { 32 | public static void main(String[] args) { 33 | SpringApplication.run(ManyToManyExampleApplication.class, args); 34 | } 35 | 36 | // Sử dụng @RequiredArgsConstructor và final để thay cho @Autowired 37 | private final PersonRepository personRepository; 38 | private final AddressRepository addressRepository; 39 | 40 | @Override 41 | @Transactional 42 | public void run(String... args) throws Exception { 43 | // Tạo ra đối tượng Address 44 | Address hanoi = Address.builder() 45 | .city("hanoi") 46 | .build(); 47 | Address hatay = Address.builder() 48 | .city("hatay") 49 | .build(); 50 | 51 | // Tạo ra đối tượng person 52 | Person person1 = Person.builder() 53 | .name("loda1") 54 | .build(); 55 | Person person2 = Person.builder() 56 | .name("loda2") 57 | .build(); 58 | 59 | // set Persons vào address 60 | hanoi.setPersons(Lists.newArrayList(person1, person2)); 61 | hatay.setPersons(Lists.newArrayList(person1)); 62 | 63 | // Lưu vào db 64 | // Chúng ta chỉ cần lưu address, vì cascade = CascadeType.ALL nên nó sẽ lưu luôn Person. 65 | addressRepository.saveAndFlush(hanoi); 66 | addressRepository.saveAndFlush(hatay); 67 | 68 | 69 | // Vào: http://localhost:8080/h2-console/ để xem dữ liệu đã insert 70 | 71 | Address queryResult = addressRepository.findById(1L).get(); 72 | System.out.println(queryResult.getCity()); 73 | System.out.println(queryResult.getPersons()); 74 | 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /jpa-hibernate-many-to-many/src/main/java/me/loda/jpa/manytomany/Person.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import java.util.Collection; 12 | 13 | import javax.persistence.CascadeType; 14 | import javax.persistence.Entity; 15 | import javax.persistence.FetchType; 16 | import javax.persistence.GeneratedValue; 17 | import javax.persistence.Id; 18 | import javax.persistence.JoinColumn; 19 | import javax.persistence.ManyToMany; 20 | import javax.persistence.ManyToOne; 21 | 22 | import lombok.AllArgsConstructor; 23 | import lombok.Builder; 24 | import lombok.Data; 25 | import lombok.EqualsAndHashCode; 26 | import lombok.NoArgsConstructor; 27 | import lombok.ToString.Exclude; 28 | 29 | /** 30 | * Copyright 2019 {@author Loda} (https://loda.me). 31 | * This project is licensed under the MIT license. 32 | * 33 | * @since 4/5/2019 34 | * Github: https://github.com/loda-kun 35 | */ 36 | @Entity 37 | @Data 38 | @NoArgsConstructor 39 | @AllArgsConstructor 40 | @Builder 41 | public class Person { 42 | 43 | @Id 44 | @GeneratedValue 45 | private Long id; 46 | private String name; 47 | 48 | // mappedBy trỏ tới tên biến persons ở trong Address. 49 | @ManyToMany(mappedBy = "persons") 50 | // LAZY để tránh việc truy xuất dữ liệu không cần thiết. Lúc nào cần thì mới query 51 | @EqualsAndHashCode.Exclude 52 | @Exclude 53 | private Collection
addresses; 54 | } 55 | -------------------------------------------------------------------------------- /jpa-hibernate-many-to-many/src/main/java/me/loda/jpa/manytomany/PersonRepository.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import org.springframework.data.jpa.repository.JpaRepository; 12 | 13 | /** 14 | * Copyright 2019 {@author Loda} (https://loda.me). 15 | * This project is licensed under the MIT license. 16 | * 17 | * @since 4/5/2019 18 | * Github: https://github.com/loda-kun 19 | */ 20 | public interface PersonRepository extends JpaRepository { 21 | } 22 | -------------------------------------------------------------------------------- /jpa-hibernate-many-to-many/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:h2:mem:testdb 2 | spring.datasource.driverClassName=org.h2.Driver 3 | spring.datasource.username=sa 4 | spring.datasource.password= 5 | 6 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 7 | # Enabling H2 Console 8 | spring.h2.console.enabled=true -------------------------------------------------------------------------------- /jpa-hibernate-one-to-many/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.4.RELEASE' 3 | id 'java' 4 | } 5 | apply plugin: 'io.spring.dependency-management' 6 | 7 | group 'me.loda.java' 8 | version '1.0-SNAPSHOT' 9 | 10 | sourceCompatibility = 1.8 11 | 12 | configurations { 13 | compileOnly { 14 | extendsFrom annotationProcessor 15 | } 16 | } 17 | 18 | repositories { 19 | mavenCentral() 20 | } 21 | 22 | dependencies { 23 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 24 | implementation 'org.springframework.boot:spring-boot-starter-web' 25 | compileOnly 'org.projectlombok:lombok' 26 | runtimeOnly 'com.h2database:h2' 27 | annotationProcessor 'org.projectlombok:lombok' 28 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 29 | } 30 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-many/readme.md: -------------------------------------------------------------------------------- 1 | # Hướng dẫn @OneToMany và @ManyToOne 2 | [https://loda.me/Huong-dan-@OneToMany-va-@ManyToOne/](https://loda.me/Huong-dan-@OneToMany-va-@ManyToOne/) -------------------------------------------------------------------------------- /jpa-hibernate-one-to-many/src/main/java/me/loda/jpa/manytomany/Address.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import java.util.Collection; 12 | 13 | import javax.persistence.CascadeType; 14 | import javax.persistence.Entity; 15 | import javax.persistence.GeneratedValue; 16 | import javax.persistence.Id; 17 | import javax.persistence.OneToMany; 18 | 19 | import lombok.AllArgsConstructor; 20 | import lombok.Data; 21 | import lombok.EqualsAndHashCode; 22 | import lombok.NoArgsConstructor; 23 | import lombok.ToString; 24 | 25 | /** 26 | * Copyright 2019 {@author Loda} (https://loda.me). 27 | * This project is licensed under the MIT license. 28 | * 29 | * @since 4/5/2019 30 | * Github: https://github.com/loda-kun 31 | */ 32 | @Entity // Đánh dấu đây là table trong db 33 | @Data // lombok giúp generate các hàm constructor, get, set v.v. 34 | @AllArgsConstructor 35 | @NoArgsConstructor 36 | public class Address { 37 | 38 | @Id //Đánh dấu là primary key 39 | @GeneratedValue // Giúp tự động tăng 40 | private Long id; 41 | 42 | private String city; 43 | private String province; 44 | 45 | @OneToMany(mappedBy = "address", cascade = CascadeType.ALL) // Quan hệ 1-n với đối tượng ở dưới (Person) (1 địa điểm có nhiều người ở) 46 | // MapopedBy trỏ tới tên biến Address ở trong Person. 47 | @EqualsAndHashCode.Exclude // không sử dụng trường này trong equals và hashcode 48 | @ToString.Exclude // Khoonhg sử dụng trong toString() 49 | private Collection persons; 50 | } 51 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-many/src/main/java/me/loda/jpa/manytomany/AddressRepository.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import org.springframework.data.jpa.repository.JpaRepository; 12 | 13 | /** 14 | * Copyright 2019 {@author Loda} (https://loda.me). 15 | * This project is licensed under the MIT license. 16 | * 17 | * @since 4/5/2019 18 | * Github: https://github.com/loda-kun 19 | */ 20 | // Kế thừa JpaRepository để giao tiếp với database 21 | public interface AddressRepository extends JpaRepository { 22 | } 23 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-many/src/main/java/me/loda/jpa/manytomany/OneToManyExampleApplication.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import java.util.Collections; 12 | 13 | import javax.transaction.Transactional; 14 | 15 | import org.springframework.boot.CommandLineRunner; 16 | import org.springframework.boot.SpringApplication; 17 | import org.springframework.boot.autoconfigure.SpringBootApplication; 18 | 19 | import lombok.RequiredArgsConstructor; 20 | 21 | /** 22 | * Copyright 2019 {@author Loda} (https://loda.me). 23 | * This project is licensed under the MIT license. 24 | * 25 | * @since 4/5/2019 26 | * Github: https://github.com/loda-kun 27 | */ 28 | @SpringBootApplication 29 | @RequiredArgsConstructor 30 | public class OneToManyExampleApplication implements CommandLineRunner { 31 | public static void main(String[] args) { 32 | SpringApplication.run(OneToManyExampleApplication.class, args); 33 | } 34 | 35 | // Sử dụng @RequiredArgsConstructor và final để thay cho @Autowired 36 | private final PersonRepository personRepository; 37 | private final AddressRepository addressRepository; 38 | 39 | @Override 40 | public void run(String... args) throws Exception { 41 | // Tạo ra đối tượng Address có tham chiếu tới person 42 | Address address = new Address(); 43 | address.setCity("Hanoi"); 44 | 45 | // Tạo ra đối tượng person 46 | Person person = new Person(); 47 | person.setName("loda"); 48 | person.setAddress(address); 49 | 50 | address.setPersons(Collections.singleton(person)); 51 | // Lưu vào db 52 | // Chúng ta chỉ cần lưu address, vì cascade = CascadeType.ALL nên nó sẽ lưu luôn Person. 53 | addressRepository.saveAndFlush(address); 54 | 55 | 56 | // Vào: http://localhost:8080/h2-console/ để xem dữ liệu đã insert 57 | 58 | personRepository.findAll().forEach(p -> { 59 | System.out.println(p.getId()); 60 | System.out.println(p.getName()); 61 | System.out.println(p.getAddress()); 62 | }); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-many/src/main/java/me/loda/jpa/manytomany/Person.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import javax.persistence.Entity; 12 | import javax.persistence.GeneratedValue; 13 | import javax.persistence.Id; 14 | import javax.persistence.JoinColumn; 15 | import javax.persistence.ManyToOne; 16 | 17 | import lombok.AllArgsConstructor; 18 | import lombok.Data; 19 | import lombok.EqualsAndHashCode; 20 | import lombok.NoArgsConstructor; 21 | import lombok.ToString; 22 | 23 | /** 24 | * Copyright 2019 {@author Loda} (https://loda.me). 25 | * This project is licensed under the MIT license. 26 | * 27 | * @since 4/5/2019 28 | * Github: https://github.com/loda-kun 29 | */ 30 | @Entity 31 | @Data 32 | @NoArgsConstructor 33 | @AllArgsConstructor 34 | public class Person { 35 | 36 | @Id 37 | @GeneratedValue 38 | private Long id; 39 | private String name; 40 | 41 | // Many to One Có nhiều người ở 1 địa điểm. 42 | @ManyToOne // LAZY để tránh việc truy xuất dữ liệu không cần thiết. Lúc nào cần thì mới query 43 | @JoinColumn(name = "address_id") // thông qua khóa ngoại address_id 44 | @EqualsAndHashCode.Exclude 45 | @ToString.Exclude 46 | private Address address; 47 | } 48 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-many/src/main/java/me/loda/jpa/manytomany/PersonRepository.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import org.springframework.data.jpa.repository.JpaRepository; 12 | 13 | /** 14 | * Copyright 2019 {@author Loda} (https://loda.me). 15 | * This project is licensed under the MIT license. 16 | * 17 | * @since 4/5/2019 18 | * Github: https://github.com/loda-kun 19 | */ 20 | public interface PersonRepository extends JpaRepository { 21 | } 22 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-many/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:h2:mem:testdb 2 | spring.datasource.driverClassName=org.h2.Driver 3 | spring.datasource.username=sa 4 | spring.datasource.password= 5 | 6 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 7 | # Enabling H2 Console 8 | spring.h2.console.enabled=true -------------------------------------------------------------------------------- /jpa-hibernate-one-to-one/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.4.RELEASE' 3 | id 'java' 4 | } 5 | apply plugin: 'io.spring.dependency-management' 6 | 7 | group 'me.loda.java' 8 | version '1.0-SNAPSHOT' 9 | 10 | sourceCompatibility = 1.8 11 | 12 | configurations { 13 | compileOnly { 14 | extendsFrom annotationProcessor 15 | } 16 | } 17 | 18 | repositories { 19 | mavenCentral() 20 | } 21 | 22 | dependencies { 23 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 24 | implementation 'org.springframework.boot:spring-boot-starter-web' 25 | compileOnly 'org.projectlombok:lombok' 26 | runtimeOnly 'com.h2database:h2' 27 | annotationProcessor 'org.projectlombok:lombok' 28 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 29 | } 30 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-one/readme.md: -------------------------------------------------------------------------------- 1 | # Hướng dẫn @OneToOne 2 | [https://loda.me/Huong-dan-su-dung-@OneToOne-Relationship/](https://loda.me/Huong-dan-su-dung-@OneToOne-Relationship/) -------------------------------------------------------------------------------- /jpa-hibernate-one-to-one/src/main/java/me/loda/jpa/manytomany/Address.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import javax.persistence.Entity; 12 | import javax.persistence.GeneratedValue; 13 | import javax.persistence.Id; 14 | import javax.persistence.JoinColumn; 15 | import javax.persistence.OneToOne; 16 | 17 | import lombok.Builder; 18 | import lombok.Data; 19 | 20 | /** 21 | * Copyright 2019 {@author Loda} (https://loda.me). 22 | * This project is licensed under the MIT license. 23 | * 24 | * @since 4/5/2019 25 | * Github: https://github.com/loda-kun 26 | */ 27 | @Entity // Đánh dấu đây là table trong db 28 | @Data // lombok giúp generate các hàm constructor, get, set v.v. 29 | @Builder // lombok giúp tạo class builder 30 | public class Address { 31 | 32 | @Id //Đánh dấu là primary key 33 | @GeneratedValue // Giúp tự động tăng 34 | private Long id; 35 | 36 | private String city; 37 | private String province; 38 | 39 | @OneToOne // Quan hệ 1-1 với đối tượng ở dưới (Person) 40 | @JoinColumn(name = "person_id") // thông qua khóa ngoại person_id 41 | private Person person; 42 | } 43 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-one/src/main/java/me/loda/jpa/manytomany/AddressRepository.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import org.springframework.data.jpa.repository.JpaRepository; 12 | 13 | /** 14 | * Copyright 2019 {@author Loda} (https://loda.me). 15 | * This project is licensed under the MIT license. 16 | * 17 | * @since 4/5/2019 18 | * Github: https://github.com/loda-kun 19 | */ 20 | // Kế thừa JpaRepository để giao tiếp với database 21 | public interface AddressRepository extends JpaRepository { 22 | } 23 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-one/src/main/java/me/loda/jpa/manytomany/OneToOneExampleApplication.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import org.springframework.boot.CommandLineRunner; 12 | import org.springframework.boot.SpringApplication; 13 | import org.springframework.boot.autoconfigure.SpringBootApplication; 14 | 15 | import lombok.RequiredArgsConstructor; 16 | 17 | /** 18 | * Copyright 2019 {@author Loda} (https://loda.me). 19 | * This project is licensed under the MIT license. 20 | * 21 | * @since 4/5/2019 22 | * Github: https://github.com/loda-kun 23 | */ 24 | @SpringBootApplication 25 | @RequiredArgsConstructor 26 | public class OneToOneExampleApplication implements CommandLineRunner { 27 | public static void main(String[] args) { 28 | SpringApplication.run(OneToOneExampleApplication.class, args); 29 | } 30 | 31 | // Sử dụng @RequiredArgsConstructor và final để thay cho @Autowired 32 | private final PersonRepository personRepository; 33 | private final AddressRepository addressRepository; 34 | 35 | @Override 36 | public void run(String... args) throws Exception { 37 | // Tạo ra đối tượng person 38 | Person person = Person.builder() 39 | .name("loda") 40 | .build(); 41 | // Lưu vào db 42 | personRepository.save(person); 43 | 44 | // Tạo ra đối tượng Address có tham chiếu tới person 45 | Address address = Address.builder() 46 | .city("Hanoi") 47 | .person(person) 48 | .build(); 49 | 50 | // Lưu vào db 51 | addressRepository.save(address); 52 | 53 | // Vào: http://localhost:8080/h2-console/ để xem dữ liệu đã insert 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-one/src/main/java/me/loda/jpa/manytomany/Person.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import javax.persistence.Entity; 12 | import javax.persistence.GeneratedValue; 13 | import javax.persistence.Id; 14 | 15 | import lombok.Builder; 16 | import lombok.Data; 17 | 18 | /** 19 | * Copyright 2019 {@author Loda} (https://loda.me). 20 | * This project is licensed under the MIT license. 21 | * 22 | * @since 4/5/2019 23 | * Github: https://github.com/loda-kun 24 | */ 25 | @Entity 26 | @Data 27 | @Builder 28 | public class Person { 29 | 30 | @Id 31 | @GeneratedValue 32 | private Long id; 33 | private String name; 34 | 35 | } 36 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-one/src/main/java/me/loda/jpa/manytomany/PersonRepository.java: -------------------------------------------------------------------------------- 1 | package me.loda.jpa.manytomany; 2 | /******************************************************* 3 | * For Vietnamese readers: 4 | * Các bạn thân mến, mình rất vui nếu project này giúp 5 | * ích được cho các bạn trong việc học tập và công việc. Nếu 6 | * bạn sử dụng lại toàn bộ hoặc một phần source code xin để 7 | * lại dường dẫn tới github hoặc tên tác giá. 8 | * Xin cảm ơn! 9 | *******************************************************/ 10 | 11 | import org.springframework.data.jpa.repository.JpaRepository; 12 | 13 | /** 14 | * Copyright 2019 {@author Loda} (https://loda.me). 15 | * This project is licensed under the MIT license. 16 | * 17 | * @since 4/5/2019 18 | * Github: https://github.com/loda-kun 19 | */ 20 | public interface PersonRepository extends JpaRepository { 21 | } 22 | -------------------------------------------------------------------------------- /jpa-hibernate-one-to-one/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:h2:mem:testdb 2 | spring.datasource.driverClassName=org.h2.Driver 3 | spring.datasource.username=sa 4 | spring.datasource.password= 5 | 6 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 7 | # Enabling H2 Console 8 | spring.h2.console.enabled=true -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'all' 2 | include 'java-reflection-annotations' 3 | include 'java-security-jwt' 4 | include 'jpa-hibernate-one-to-one' 5 | include 'jpa-hibernate-one-to-many' 6 | include 'jpa-hibernate-many-to-many' 7 | include 'java-thread-pool-executor' 8 | include 'java-threadpoolexecutor' 9 | 10 | --------------------------------------------------------------------------------