├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main └── kotlin │ ├── example01 │ ├── Example01Mapper.kt │ └── Example01Model.kt │ ├── example02 │ ├── Example02Mapper.kt │ ├── Example02Model.kt │ └── oldmybatis │ │ ├── Example02OldMyBatisMapper.kt │ │ └── Example02OldMyBatisModel.kt │ ├── example03 │ ├── Example03Mapper.kt │ └── Example03Model.kt │ ├── example04 │ ├── Example04Mapper.kt │ ├── Example04Mapper.xml │ ├── Example04Model.kt │ └── lazy │ │ ├── Example04LazyMapper.kt │ │ └── Example04LazyModel.kt │ ├── example05 │ ├── Example05Model.kt │ ├── PersonDynamicSqlSupport.kt │ └── PersonMapper.kt │ ├── example06 │ ├── GeneratedAlwaysDynamicSqlSupport.kt │ ├── GeneratedAlwaysMapper.kt │ └── GeneratedAlwaysRow.kt │ └── util │ ├── MatchesAny.kt │ └── YesNoTypeHandler.kt └── test ├── kotlin ├── example01 │ └── Example01Test.kt ├── example02 │ ├── Example02Test.kt │ └── oldmybatis │ │ └── Example02OldMyBatisTest.kt ├── example03 │ └── Example03Test.kt ├── example04 │ ├── Example04Test.kt │ └── lazy │ │ └── Example04LazyTest.kt ├── example05 │ ├── Example05Test.kt │ └── StatementConfigurationTest.kt └── example06 │ └── Example06Test.kt └── resources └── CreateSimpleDB.sql /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set default behaviour, in case users don't have core.autocrlf set. 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gradle 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | os: [ubuntu-latest] 11 | java: [11, 17, 21, 23] 12 | distribution: ['zulu'] 13 | fail-fast: false 14 | max-parallel: 4 15 | name: Test JDK ${{ matrix.java }}, ${{ matrix.os }} 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Set up JDK 20 | uses: actions/setup-java@v3 21 | with: 22 | java-version: ${{ matrix.java }} 23 | distribution: ${{ matrix.distribution }} 24 | - name: Test with Gradle 25 | run: ./gradlew test 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | .idea 3 | .gradle 4 | build 5 | local.properties 6 | *.iml 7 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Jeff Butler 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 | # MyBatis Kotlin Examples 2 | 3 | This project demonstrates use of MyBatis with the Kotlin language. This is a work in progress, and we will update as 4 | our learnings progress and/or new capabilities in MyBatis become available. 5 | 6 | Note that in most cases we are foregoing XML and working solely with the Java API for MyBatis. Hopefully it will be 7 | clear how to translate the concepts to XML if so desired. 8 | 9 | All the code in this project is pure Kotlin. As is typical, source code is in the /src/main/kotlin 10 | directory and test code is in /src/test/kotlin. The examples described below have associated packages 11 | in the source trees. So code for example01 is in /src/main/kotlin/example01, etc. 12 | 13 | ## Using MyBatis with Kotlin 14 | 15 | One of MyBatis' core strengths is mapping SQL result sets to an object graph. MyBatis is good at these mappings for 16 | many types of class hierarchies. MyBatis can create a deeply nested object graph and its group by function 17 | provides support for creating an object graph that avoids the need for N+1 queries. However, the implementation of this 18 | result set mapping is predicated on the idea that objects can be instantiated and later modified - and this is not 19 | strictly compatible with idiomatic Kotlin. With idiomatic Kotlin, objects are created through their constructors and are 20 | immutable after creation. The examples (especially example03 and example04) will show patterns of dealing with this. 21 | 22 | ### example01 - Auto Mapping 23 | 24 | This example shows that MyBatis is able to create simple objects (basic data types, no nested classes) with idiomatic 25 | Kotlin. The "model" classes are Kotlin data classes with a mix of nullable and non-nullable types. No special mapping 26 | is needed in MyBatis. MyBatis can auto discover class constructors in this case. The important distinction is there are 27 | no nested classes or group-by functions 28 | 29 | ### example02 - Type Handlers and Advanced Auto Mapping 30 | 31 | This example shows the use of TypeHandlers. With this example we have moved beyond simple types. 32 | We are still using immutable types, but in this case we have a non-standard type that requires a 33 | TypeHandler. Important code changes: 34 | 35 | 1. Look in `/src/main/kotlin/util/YesNoTypeHandler.kt` to see how to write the type handler 36 | 1. Look in `/src/test/kotlin/example02/Example02Test.kt` to see how to register the type handler 37 | 38 | ### example02.oldmybatis - Type Handlers and Advanced Auto Mapping in Older MyBatis Versions 39 | 40 | This example shows the use of classes that need TypeHandlers in older versions of MyBatis. In MyBatis versions prior to 41 | 3.5.0, MyBatis sometimes had difficulty finding constructors on classes that included types with TypeHandlers. 42 | In that case, we need to annotate the class constructor 43 | with the `@AutomapConstructor` annotation and also register the type handler. Important code changes: 44 | 45 | 1. Look in `/src/main/kotlin/example02/oldmybatis/Example02Model.kt` to see how to annotate the class 46 | 1. Look in `/src/main/kotlin/util/YesNoTypeHandler.kt` to see how to write the type handler 47 | 1. Look in `/src/test/kotlin/example02/oldmybatis/Example02Test.kt` to see how to register the type handler 48 | 49 | ### example03 - Nested Objects 50 | 51 | This example shows how to write Kotlin for a class hierarchy where a class (Person in this case) has an 52 | attribute that is another class (Address in this case). With this example we can no longer use Kotlin 53 | immutable data classes because of the way that MyBatis constructs an object graph in cases like this. 54 | 55 | ### example04 - Join Queries with Nested Collections 56 | 57 | This example shows how to use MyBatis support for N+1 query mitigation. This involves creating a 58 | result map with a nested collection. Currently, this is only supported in MyBatis using XML to define the 59 | result map. 60 | 61 | ### example04.lazy - Lazy Loaded Nested Collections 62 | 63 | This example shows how to use MyBatis support for lazy loaded associations. This forces an N+1 query (or worse), 64 | so be careful with lazy loading. There are also issues with lazy loading and Kotlin due to the way that Javassist 65 | works (MyBatis uses Javassist to create dynamic proxies when you use lazy loading). Any class that will be 66 | lazy loaded, and any field in that class that will be lazy loaded, must be declared "open" in Kotlin. 67 | We can code queries like this without XML which is good, but the performance may be worse - tradeoffs. 68 | 69 | ### example05 - MyBatis Dynamic SQL 70 | 71 | This example shows how to use Kotlin to interact with the "MyBatis Dynamic SQL" library. 72 | This example also shows how MyBatis Generator creates code for Kotlin. 73 | 74 | ### example06 - MyBatis Dynamic SQL (Generated Values) 75 | 76 | This example shows how to use Kotlin to interact with the "MyBatis Dynamic SQL" library when a 77 | table contains generated values. 78 | This example also shows how MyBatis Generator creates code for Kotlin. 79 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | kotlin("jvm") version "2.1.10" 5 | } 6 | 7 | group = "com.github.jeffgbutler" 8 | version = "1.0.0-SNAPSHOT" 9 | 10 | java { 11 | toolchain { 12 | languageVersion.set(JavaLanguageVersion.of(17)) 13 | } 14 | } 15 | 16 | sourceSets { 17 | main { 18 | resources { 19 | srcDir("src/main/kotlin") 20 | include("**/*.xml") 21 | } 22 | } 23 | } 24 | 25 | repositories { 26 | mavenCentral() 27 | maven { 28 | url = uri("https://oss.sonatype.org/content/repositories/snapshots") 29 | } 30 | } 31 | 32 | dependencies { 33 | implementation ("org.mybatis:mybatis:3.5.19") 34 | implementation ("org.mybatis.dynamic-sql:mybatis-dynamic-sql:2.0.0-SNAPSHOT") 35 | testImplementation ("org.assertj:assertj-core:3.27.3") 36 | testImplementation ("org.hsqldb:hsqldb:2.7.4") 37 | testImplementation("org.jetbrains.kotlin:kotlin-test-junit5:2.1.10") 38 | } 39 | 40 | tasks.withType { 41 | useJUnitPlatform() 42 | } 43 | 44 | tasks.withType { 45 | compilerOptions { 46 | freeCompilerArgs.addAll("-Xjsr305=strict") 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeffgbutler/mybatis-kotlin-examples/34ad7e57b63befb61108402e8d044c1059364084/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-8.11-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "mybatis-kotlin-examples" 2 | 3 | -------------------------------------------------------------------------------- /src/main/kotlin/example01/Example01Mapper.kt: -------------------------------------------------------------------------------- 1 | package example01 2 | 3 | import org.apache.ibatis.annotations.Select 4 | 5 | interface Example01Mapper { 6 | 7 | @Select( 8 | "select id, first_name, last_name, birth_date, employed, occupation", 9 | "from Person where id = #{value}" 10 | ) 11 | fun selectPersonById(id: Int): Person 12 | } 13 | -------------------------------------------------------------------------------- /src/main/kotlin/example01/Example01Model.kt: -------------------------------------------------------------------------------- 1 | package example01 2 | 3 | import java.time.LocalDate 4 | 5 | /* 6 | * This shows that MyBatis automatic constructor mapping to Kotlin data classes is supported under many 7 | * circumstances. What's important is that the order of fields in the query, and the data types, match exactly, 8 | * or match types with registered type handlers. 9 | * 10 | * Notes: 11 | * 1. occupation is nullable in the database, so the Kotlin type should be String? 12 | * 2. birthDate here is java.time.LocalDate. MyBatis has built-in type handlers for many data types so no special 13 | * configuration is needed here. 14 | * 3. MyBatis versions prior to 3.5.0 will have difficulty finding the constructor in this class. 15 | * For that case, see the example in example02.oldmybatis f0r details on how to resolve that 16 | * issue. 17 | */ 18 | data class Person( 19 | val id: Int, 20 | val firstName: String, 21 | val lastName: String, 22 | val birthDate: LocalDate, 23 | val employed: String, 24 | val occupation: String? 25 | ) 26 | -------------------------------------------------------------------------------- /src/main/kotlin/example02/Example02Mapper.kt: -------------------------------------------------------------------------------- 1 | package example02 2 | 3 | import org.apache.ibatis.annotations.Select 4 | 5 | interface Example02Mapper { 6 | 7 | @Select( 8 | "select id, first_name, last_name, birth_date, employed, occupation", 9 | "from Person where id = #{value}" 10 | ) 11 | fun selectPersonById(id: Int): Person 12 | } 13 | -------------------------------------------------------------------------------- /src/main/kotlin/example02/Example02Model.kt: -------------------------------------------------------------------------------- 1 | package example02 2 | 3 | import java.time.LocalDate 4 | 5 | /* 6 | * In this version of the class, one thing has changed: 7 | * 8 | * 1. The data type for employed has changed to Boolean 9 | * 10 | * MyBatis has a built in type handler for java.sql.Date -> java.time.LocalDate so we don't need to write one. But we do 11 | * need to write a type handler to convert the database string to a Boolean. That type handler is 12 | * util.YesNoTypeHandler. 13 | * 14 | * Note that MyBatis version prior to 3.5.0 will have difficulty finding the constructor for a class like this that 15 | * requires type handlers. For that case, see the example on example02.oldmybatis for a workaround. 16 | * 17 | */ 18 | data class Person( 19 | val id: Int, 20 | val firstName: String, 21 | val lastName: String, 22 | val birthDate: LocalDate, 23 | val employed: Boolean, 24 | val occupation: String? 25 | ) -------------------------------------------------------------------------------- /src/main/kotlin/example02/oldmybatis/Example02OldMyBatisMapper.kt: -------------------------------------------------------------------------------- 1 | package example02.oldmybatis 2 | 3 | import org.apache.ibatis.annotations.Select 4 | 5 | interface Example02OldMyBatisMapper { 6 | 7 | @Select( 8 | "select id, first_name, last_name, birth_date, employed, occupation", 9 | "from Person where id = #{value}" 10 | ) 11 | fun selectPersonById(id: Int): Person 12 | } 13 | -------------------------------------------------------------------------------- /src/main/kotlin/example02/oldmybatis/Example02OldMyBatisModel.kt: -------------------------------------------------------------------------------- 1 | package example02.oldmybatis 2 | 3 | import org.apache.ibatis.annotations.AutomapConstructor 4 | import java.util.* 5 | 6 | /* 7 | * This version is the same as the version in example02 except for the following: 8 | * 9 | * 1. @AutomapConstructor annotation. 10 | * 2. The datatype of birthDate is java.util.Date - MyBatis versions prior to 3.4.5 did not include type 11 | * handlers for the JSR310 types 12 | * 13 | * MyBatis versions prior to version 3.5.0 sometimes had difficulty finding constructors when there were 14 | * constructor parameters that required type handlers. In those cases, you can use the @AutomapConstructor annotation 15 | * to designate a constructor for MyBatis. 16 | * 17 | */ 18 | data class Person @AutomapConstructor constructor( 19 | val id: Int, 20 | val firstName: String, 21 | val lastName: String, 22 | val birthDate: Date, 23 | val employed: Boolean, 24 | val occupation: String? 25 | ) -------------------------------------------------------------------------------- /src/main/kotlin/example03/Example03Mapper.kt: -------------------------------------------------------------------------------- 1 | package example03 2 | 3 | import org.apache.ibatis.annotations.Result 4 | import org.apache.ibatis.annotations.Results 5 | import org.apache.ibatis.annotations.Select 6 | import util.YesNoTypeHandler 7 | 8 | interface Example03Mapper { 9 | 10 | @Select( 11 | "select p.id, p.first_name, p.last_name, p.birth_date, p.employed, p.occupation, a.id as address_id, a.street_address, a.city, a.state", 12 | "from Person p join Address a on p.address_id = a.id", 13 | "where p.id = #{value}" 14 | ) 15 | @Results( 16 | Result(column = "id", property = "id"), 17 | Result(column = "first_name", property = "firstName"), 18 | Result(column = "last_name", property = "lastName"), 19 | Result(column = "birth_date", property = "birthDate"), 20 | Result(column = "employed", property = "employed", typeHandler = YesNoTypeHandler::class), 21 | Result(column = "occupation", property = "occupation"), 22 | Result(column = "address_id", property = "address.id"), 23 | Result(column = "street_address", property = "address.streetAddress"), 24 | Result(column = "city", property = "address.city"), 25 | Result(column = "state", property = "address.state") 26 | ) 27 | fun selectPersonById(id: Int): PersonWithAddress 28 | } 29 | -------------------------------------------------------------------------------- /src/main/kotlin/example03/Example03Model.kt: -------------------------------------------------------------------------------- 1 | package example03 2 | 3 | import java.time.LocalDate 4 | 5 | /* 6 | * In this version of the model, we have added an Address class and then made address an attribute of a person. 7 | * Kotlin's data classes require all attributes to be initialized on the constructor and this is incompatible 8 | * with how MyBatis builds result objects. Therefore, the model is now plain Kotlin classes. 9 | * 10 | * Because we are no longer using constructor based classes, we now define the result mappings with the @Results 11 | * annotation in the mapper interface. 12 | * 13 | * Note the use of lateinit - this allows the class to be constructed, but the values of the properties can be set 14 | * after construction. This works well, but has some limitations: 15 | * 16 | * 1. Primitive data types (Int and Boolean in this case) cannot have lateinit values - so we set a default 17 | * 2. Nullable fields (occupation in this case) cannot have lateinit - so we set them to null by default 18 | * 3. Nested classes (the address attribute of PersonWithAddress) should be initialized in their enclosing classes. 19 | * Kotlin would allow lateinit for nested classes, but that won't work with MyBatis because MyBatis will do a "get" 20 | * on the nested class, and "get" is not allowed until the class has been initialized. If the nested class is 21 | * nullable, it will work to initialize the property as "null" - MyBatis can create an instance in that case. 22 | */ 23 | 24 | class Address { 25 | var id: Int = 0 26 | lateinit var streetAddress: String 27 | lateinit var city: String 28 | lateinit var state: String 29 | } 30 | 31 | class PersonWithAddress { 32 | var id: Int = 0 33 | lateinit var firstName: String 34 | lateinit var lastName: String 35 | lateinit var birthDate: LocalDate 36 | var employed: Boolean = false 37 | var occupation: String? = null 38 | var address: Address = Address() 39 | } 40 | 41 | -------------------------------------------------------------------------------- /src/main/kotlin/example04/Example04Mapper.kt: -------------------------------------------------------------------------------- 1 | package example04 2 | 3 | import org.apache.ibatis.annotations.ResultMap 4 | import org.apache.ibatis.annotations.Select 5 | 6 | interface Example04Mapper { 7 | 8 | @Select( 9 | "select a.id, a.street_address, a.city, a.state, p.id as person_id, p.first_name, p.last_name, p.birth_date, p.employed, p.occupation", 10 | "from Address a join Person p on a.id = p.address_id", 11 | "where a.id = #{value}" 12 | ) 13 | @ResultMap("AddressWithPeopleResult") 14 | fun selectAddressById(id: Int): AddressWithPeople 15 | } 16 | -------------------------------------------------------------------------------- /src/main/kotlin/example04/Example04Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/kotlin/example04/Example04Model.kt: -------------------------------------------------------------------------------- 1 | package example04 2 | 3 | import java.time.LocalDate 4 | 5 | /* 6 | * In this version of the model, we have an AddressWithPeople class that includes a nested list of the Persons with the 7 | * address. This shows how to code a join. You will note that the mapper makes reference to an XML file for the result 8 | * mapping - this is because the MyBatis annotations cannot be used to describe nested collections. 9 | * 10 | * Note that the nested list must be mutable, and must be initialized. MyBatis builds objects incrementally 11 | * with every row returned from a query, so it is not possible to use a non-mutable list. 12 | */ 13 | 14 | class AddressWithPeople { 15 | var id: Int = 0 16 | lateinit var streetAddress: String 17 | lateinit var city: String 18 | lateinit var state: String 19 | val people = mutableListOf() 20 | } 21 | 22 | class Person { 23 | var id: Int = 0 24 | lateinit var firstName: String 25 | lateinit var lastName: String 26 | lateinit var birthDate: LocalDate 27 | var employed: Boolean = false 28 | var occupation: String? = null 29 | } 30 | 31 | -------------------------------------------------------------------------------- /src/main/kotlin/example04/lazy/Example04LazyMapper.kt: -------------------------------------------------------------------------------- 1 | package example04.lazy 2 | 3 | import org.apache.ibatis.annotations.* 4 | import org.apache.ibatis.mapping.FetchType 5 | import util.YesNoTypeHandler 6 | 7 | // In this mapper we code two queries because we want to lazy load the nested list. This forces an 8 | // N + 1 query, so use with caution 9 | 10 | interface Example04LazyMapper { 11 | 12 | @Select( 13 | "select id, street_address, city, state", 14 | "from Address", 15 | "where id = #{value}" 16 | ) 17 | @Results( 18 | Result(column = "id", property = "id", id = true), 19 | Result(column = "street_address", property = "streetAddress"), 20 | Result(column = "city", property = "city"), 21 | Result(column = "state", property = "state"), 22 | Result(column = "id", property = "people", many = Many(fetchType = FetchType.LAZY, select = "selectPeopleByAddressId" )) 23 | ) 24 | fun selectAddressById(id: Int): AddressWithPeople 25 | 26 | @Select( 27 | "select id, first_name, last_name, birth_date, employed, occupation", 28 | "from Person", 29 | "where address_id = #{value}" 30 | ) 31 | @Results( 32 | Result(column = "id", property = "id"), 33 | Result(column = "first_name", property = "firstName"), 34 | Result(column = "last_name", property = "lastName"), 35 | Result(column = "birth_date", property = "birthDate"), 36 | Result(column = "employed", property = "employed", typeHandler = YesNoTypeHandler::class), 37 | Result(column = "occupation", property = "occupation") 38 | ) 39 | fun selectPeopleByAddressId(addressId: Int): List 40 | } 41 | -------------------------------------------------------------------------------- /src/main/kotlin/example04/lazy/Example04LazyModel.kt: -------------------------------------------------------------------------------- 1 | package example04.lazy 2 | 3 | import java.time.LocalDate 4 | 5 | /* 6 | * In this version of the model, we have an AddressWithPeople class that includes a nested list of the Persons with the 7 | * address. This shows how to code a lazy loaded association. 8 | * 9 | * In this version, we expect the nested list to be populated by a second query, so we can declare it 10 | * as a "lateinit var" like the other properties. 11 | * 12 | * Important notes: when enabling lazy loading, MyBatis uses Javassist to create proxies for classes. Javassist 13 | * will not create a proxy for any final class or method - which is default in Kotlin. So note below that 14 | * the class AddressWithPeople is declared as open, and also the field people is declared open. Without these 15 | * declarations, lazy loading will fail. 16 | */ 17 | 18 | open class AddressWithPeople { 19 | var id: Int = 0 20 | lateinit var streetAddress: String 21 | lateinit var city: String 22 | lateinit var state: String 23 | open lateinit var people: List 24 | } 25 | 26 | class Person { 27 | var id: Int = 0 28 | lateinit var firstName: String 29 | lateinit var lastName: String 30 | lateinit var birthDate: LocalDate 31 | var employed: Boolean = false 32 | var occupation: String? = null 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/main/kotlin/example05/Example05Model.kt: -------------------------------------------------------------------------------- 1 | package example05 2 | 3 | import java.time.LocalDate 4 | 5 | data class PersonRecord( 6 | val id: Int? = null, 7 | val firstName: String? = null, 8 | val lastName: String? = null, 9 | val birthDate: LocalDate? = null, 10 | val employed: Boolean? = null, 11 | val occupation: String? = null, 12 | val addressId: Int? = null, 13 | val parentId: Int? = null 14 | ) 15 | -------------------------------------------------------------------------------- /src/main/kotlin/example05/PersonDynamicSqlSupport.kt: -------------------------------------------------------------------------------- 1 | package example05 2 | 3 | import org.mybatis.dynamic.sql.SqlTable 4 | import org.mybatis.dynamic.sql.util.kotlin.elements.column 5 | import java.sql.JDBCType 6 | import java.time.LocalDate 7 | 8 | object PersonDynamicSqlSupport { 9 | val person = Person() 10 | val id = person.id 11 | val firstName = person.firstName 12 | val lastName = person.lastName 13 | val birthDate = person.birthDate 14 | val employed = person.employed 15 | val occupation = person.occupation 16 | val addressId = person.addressId 17 | val parentId = person.parentId 18 | 19 | class Person : SqlTable("Person") { 20 | val id = column(name = "id", jdbcType = JDBCType.INTEGER) 21 | val firstName = column(name = "first_name", jdbcType = JDBCType.VARCHAR) 22 | val lastName = column(name = "last_name", jdbcType = JDBCType.VARCHAR) 23 | val birthDate = column(name = "birth_date", jdbcType = JDBCType.DATE) 24 | val employed = column( 25 | name = "employed", 26 | jdbcType = JDBCType.VARCHAR, 27 | typeHandler = "util.YesNoTypeHandler" 28 | ) 29 | val occupation = column(name = "occupation", jdbcType = JDBCType.VARCHAR) 30 | val addressId = column(name = "address_id", jdbcType = JDBCType.INTEGER) 31 | val parentId = column(name = "parent_id", jdbcType = JDBCType.INTEGER) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/kotlin/example05/PersonMapper.kt: -------------------------------------------------------------------------------- 1 | package example05 2 | 3 | import example05.PersonDynamicSqlSupport.addressId 4 | import example05.PersonDynamicSqlSupport.birthDate 5 | import example05.PersonDynamicSqlSupport.employed 6 | import example05.PersonDynamicSqlSupport.firstName 7 | import example05.PersonDynamicSqlSupport.id 8 | import example05.PersonDynamicSqlSupport.lastName 9 | import example05.PersonDynamicSqlSupport.occupation 10 | import example05.PersonDynamicSqlSupport.parentId 11 | import example05.PersonDynamicSqlSupport.person 12 | import org.apache.ibatis.annotations.Result 13 | import org.apache.ibatis.annotations.ResultMap 14 | import org.apache.ibatis.annotations.Results 15 | import org.apache.ibatis.annotations.SelectProvider 16 | import org.mybatis.dynamic.sql.select.render.SelectStatementProvider 17 | import org.mybatis.dynamic.sql.util.SqlProviderAdapter 18 | import org.mybatis.dynamic.sql.util.kotlin.CountCompleter 19 | import org.mybatis.dynamic.sql.util.kotlin.DeleteCompleter 20 | import org.mybatis.dynamic.sql.util.kotlin.KotlinUpdateBuilder 21 | import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter 22 | import org.mybatis.dynamic.sql.util.kotlin.UpdateCompleter 23 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom 24 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.deleteFrom 25 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insert 26 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertBatch 27 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertMultiple 28 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectDistinct 29 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectList 30 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectOne 31 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.update 32 | import org.mybatis.dynamic.sql.util.mybatis3.CommonCountMapper 33 | import org.mybatis.dynamic.sql.util.mybatis3.CommonDeleteMapper 34 | import org.mybatis.dynamic.sql.util.mybatis3.CommonInsertMapper 35 | import org.mybatis.dynamic.sql.util.mybatis3.CommonUpdateMapper 36 | import util.YesNoTypeHandler 37 | 38 | // This mapper uses the common base mappers supplied by MyBatis Dynamic SQL. 39 | // Use of the common insert mapper is appropriate when there are NOT generated values in the table. 40 | // In this case, only the select methods need to be written because we need to supply a 41 | // result map. 42 | 43 | interface PersonMapper : CommonCountMapper, CommonDeleteMapper, CommonInsertMapper, CommonUpdateMapper { 44 | @SelectProvider(type = SqlProviderAdapter::class, method = "select") 45 | @Results( 46 | id = "PersonRecordResult", value = [ 47 | Result(column = "a_id", property = "id"), 48 | Result(column = "first_name", property = "firstName"), 49 | Result(column = "last_name", property = "lastName"), 50 | Result(column = "birth_date", property = "birthDate"), 51 | Result(column = "employed", property = "employed", typeHandler = YesNoTypeHandler::class), 52 | Result(column = "occupation", property = "occupation"), 53 | Result(column = "address_id", property = "addressId"), 54 | Result(column = "parent_id", property = "parentId") 55 | ] 56 | ) 57 | fun selectMany(selectStatement: SelectStatementProvider): List 58 | 59 | @SelectProvider(type = SqlProviderAdapter::class, method = "select") 60 | @ResultMap("PersonRecordResult") 61 | fun selectOne(selectStatement: SelectStatementProvider): PersonRecord? 62 | } 63 | 64 | fun PersonMapper.count(completer: CountCompleter) = 65 | countFrom(this::count, person, completer) 66 | 67 | fun PersonMapper.delete(completer: DeleteCompleter) = 68 | deleteFrom(this::delete, person, completer) 69 | 70 | fun PersonMapper.deleteByPrimaryKey(id_: Int) = 71 | delete { 72 | where { id isEqualTo id_ } 73 | } 74 | 75 | fun PersonMapper.insert(row: PersonRecord) = 76 | insert(this::insert, row, person) { 77 | map(id) toProperty "id" 78 | map(firstName) toProperty "firstName" 79 | map(lastName) toProperty "lastName" 80 | map(birthDate) toProperty "birthDate" 81 | map(employed) toProperty "employed" 82 | map(occupation) toProperty "occupation" 83 | map(addressId) toProperty "addressId" 84 | map(parentId) toProperty "parentId" 85 | } 86 | 87 | fun PersonMapper.insertBatch(vararg records: PersonRecord) = 88 | insertBatch(records.toList()) 89 | 90 | fun PersonMapper.insertBatch(records: List) = 91 | insertBatch(this::insert, records, person) { 92 | map(id) toProperty "id" 93 | map(firstName) toProperty "firstName" 94 | map(lastName) toProperty "lastName" 95 | map(birthDate) toProperty "birthDate" 96 | map(employed) toProperty "employed" 97 | map(occupation) toProperty "occupation" 98 | map(addressId) toProperty "addressId" 99 | map(parentId) toProperty "parentId" 100 | } 101 | 102 | fun PersonMapper.insertMultiple(vararg records: PersonRecord) = 103 | insertMultiple(records.toList()) 104 | 105 | fun PersonMapper.insertMultiple(records: List) = 106 | insertMultiple( 107 | this::insertMultiple, 108 | records, 109 | person 110 | ) { 111 | map(id) toProperty "id" 112 | map(firstName) toProperty "firstName" 113 | map(lastName) toProperty "lastName" 114 | map(birthDate) toProperty "birthDate" 115 | map(employed) toProperty "employed" 116 | map(occupation) toProperty "occupation" 117 | map(addressId) toProperty "addressId" 118 | map(parentId) toProperty "parentId" 119 | } 120 | 121 | private val columnList = listOf( 122 | id.`as`("A_ID"), 123 | firstName, 124 | lastName, 125 | birthDate, 126 | employed, 127 | occupation, 128 | addressId 129 | ) 130 | 131 | fun PersonMapper.selectOne(completer: SelectCompleter) = 132 | selectOne( 133 | this::selectOne, 134 | columnList, 135 | person, 136 | completer 137 | ) 138 | 139 | fun PersonMapper.select(completer: SelectCompleter) = 140 | selectList(this::selectMany, columnList, person, completer) 141 | 142 | fun PersonMapper.selectDistinct(completer: SelectCompleter) = 143 | selectDistinct( 144 | this::selectMany, 145 | columnList, 146 | person, 147 | completer 148 | ) 149 | 150 | fun PersonMapper.selectByPrimaryKey(id_: Int) = 151 | selectOne { 152 | where { id isEqualTo id_ } 153 | } 154 | 155 | fun PersonMapper.update(completer: UpdateCompleter) = 156 | update(this::update, person, completer) 157 | 158 | fun PersonMapper.updateByPrimaryKey(row: PersonRecord) = 159 | update { 160 | set(firstName) equalToOrNull row::firstName 161 | set(lastName) equalToOrNull row::lastName 162 | set(birthDate) equalToOrNull row::birthDate 163 | set(employed) equalToOrNull row::employed 164 | set(occupation) equalToOrNull row::occupation 165 | set(addressId) equalToOrNull row::addressId 166 | set(parentId) equalToOrNull row::parentId 167 | where { id isEqualTo row.id!! } 168 | } 169 | 170 | fun PersonMapper.updateByPrimaryKeySelective(row: PersonRecord) = 171 | update { 172 | set(firstName) equalToWhenPresent row::firstName 173 | set(lastName) equalToWhenPresent row::lastName 174 | set(birthDate) equalToWhenPresent row::birthDate 175 | set(employed) equalToWhenPresent row::employed 176 | set(occupation) equalToWhenPresent row::occupation 177 | set(addressId) equalToWhenPresent row::addressId 178 | set(parentId) equalToWhenPresent row::parentId 179 | where { id isEqualTo row.id!! } 180 | } 181 | 182 | fun KotlinUpdateBuilder.updateAllColumns(row: PersonRecord) = 183 | apply { 184 | set(id) equalToOrNull row::id 185 | set(firstName) equalToOrNull row::firstName 186 | set(lastName) equalToOrNull row::lastName 187 | set(birthDate) equalToOrNull row::birthDate 188 | set(employed) equalToOrNull row::employed 189 | set(occupation) equalToOrNull row::occupation 190 | set(addressId) equalToOrNull row::addressId 191 | set(parentId) equalToOrNull row::parentId 192 | } 193 | 194 | fun KotlinUpdateBuilder.updateSelectiveColumns(row: PersonRecord) = 195 | apply { 196 | set(id) equalToWhenPresent row::id 197 | set(firstName) equalToWhenPresent row::firstName 198 | set(lastName) equalToWhenPresent row::lastName 199 | set(birthDate) equalToWhenPresent row::birthDate 200 | set(employed) equalToWhenPresent row::employed 201 | set(occupation) equalToWhenPresent row::occupation 202 | set(addressId) equalToWhenPresent row::addressId 203 | set(parentId) equalToWhenPresent row::parentId 204 | } 205 | -------------------------------------------------------------------------------- /src/main/kotlin/example06/GeneratedAlwaysDynamicSqlSupport.kt: -------------------------------------------------------------------------------- 1 | package example06 2 | 3 | import org.mybatis.dynamic.sql.SqlTable 4 | import org.mybatis.dynamic.sql.util.kotlin.elements.column 5 | import java.sql.JDBCType 6 | 7 | object GeneratedAlwaysDynamicSqlSupport { 8 | val generatedAlways = GeneratedAlways() 9 | val id = generatedAlways.id 10 | val firstName = generatedAlways.firstName 11 | val lastName = generatedAlways.lastName 12 | val fullName = generatedAlways.fullName 13 | 14 | class GeneratedAlways : SqlTable("GeneratedAlways") { 15 | val id = column(name = "id", jdbcType = JDBCType.INTEGER) 16 | val firstName = column(name = "first_name", jdbcType = JDBCType.VARCHAR) 17 | val lastName = column(name = "last_name", jdbcType = JDBCType.VARCHAR) 18 | val fullName = column(name = "full_name", jdbcType = JDBCType.VARCHAR) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/kotlin/example06/GeneratedAlwaysMapper.kt: -------------------------------------------------------------------------------- 1 | package example06 2 | 3 | import example06.GeneratedAlwaysDynamicSqlSupport.firstName 4 | import example06.GeneratedAlwaysDynamicSqlSupport.fullName 5 | import example06.GeneratedAlwaysDynamicSqlSupport.generatedAlways 6 | import example06.GeneratedAlwaysDynamicSqlSupport.id 7 | import example06.GeneratedAlwaysDynamicSqlSupport.lastName 8 | import org.apache.ibatis.annotations.Flush 9 | import org.apache.ibatis.annotations.InsertProvider 10 | import org.apache.ibatis.annotations.Options 11 | import org.apache.ibatis.annotations.Param 12 | import org.apache.ibatis.annotations.Result 13 | import org.apache.ibatis.annotations.ResultMap 14 | import org.apache.ibatis.annotations.Results 15 | import org.apache.ibatis.annotations.SelectProvider 16 | import org.apache.ibatis.executor.BatchResult 17 | import org.mybatis.dynamic.sql.insert.render.GeneralInsertStatementProvider 18 | import org.mybatis.dynamic.sql.insert.render.InsertStatementProvider 19 | import org.mybatis.dynamic.sql.select.render.SelectStatementProvider 20 | import org.mybatis.dynamic.sql.util.SqlProviderAdapter 21 | import org.mybatis.dynamic.sql.util.kotlin.CountCompleter 22 | import org.mybatis.dynamic.sql.util.kotlin.DeleteCompleter 23 | import org.mybatis.dynamic.sql.util.kotlin.KotlinUpdateBuilder 24 | import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter 25 | import org.mybatis.dynamic.sql.util.kotlin.UpdateCompleter 26 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom 27 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.deleteFrom 28 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insert 29 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertBatch 30 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertMultipleWithGeneratedKeys 31 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectDistinct 32 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectList 33 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectOne 34 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.update 35 | import org.mybatis.dynamic.sql.util.mybatis3.CommonCountMapper 36 | import org.mybatis.dynamic.sql.util.mybatis3.CommonDeleteMapper 37 | import org.mybatis.dynamic.sql.util.mybatis3.CommonUpdateMapper 38 | 39 | // This mapper uses the common base mappers supplied by MyBatis Dynamic SQL. 40 | // However, this mapper does NOT use the common insert mapper. When there are generated values 41 | // in the table you must write your own insert methods and supply the @Options 42 | // annotation if you with to retrieve generated values after the insert. MyBatis supports 43 | // returning generated keys from any type of insert statement (single row, multi-row, and batch). 44 | // The various insert statements below show how to code the @Options annotation properly 45 | // for each case. 46 | 47 | interface GeneratedAlwaysMapper: CommonCountMapper, CommonDeleteMapper, CommonUpdateMapper { 48 | @InsertProvider(type = SqlProviderAdapter::class, method = "insert") 49 | @Options(useGeneratedKeys = true, keyProperty = "row.id,row.fullName", keyColumn = "id,full_name") 50 | fun insert(insertStatement: InsertStatementProvider): Int 51 | 52 | @InsertProvider(type = SqlProviderAdapter::class, method = "generalInsert") 53 | @Options(useGeneratedKeys = true, keyProperty = "parameters.id,parameters.fullName", keyColumn = "id,full_name") 54 | fun generalInsert(insertStatement: GeneralInsertStatementProvider): Int 55 | 56 | @InsertProvider(type = SqlProviderAdapter::class, method = "insertMultipleWithGeneratedKeys") 57 | @Options(useGeneratedKeys = true, keyProperty = "records.id,records.fullName", keyColumn = "id,full_name") 58 | fun insertMultiple(insertStatement: String, @Param("records") records: List): Int 59 | 60 | @Flush 61 | fun flush(): List 62 | 63 | @SelectProvider(type = SqlProviderAdapter::class, method = "select") 64 | @Results( 65 | id = "GeneratedAlwaysResult", value = [ 66 | Result(column = "id", property = "id"), 67 | Result(column = "first_name", property = "firstName"), 68 | Result(column = "last_name", property = "lastName"), 69 | Result(column = "full_name", property = "fullName") 70 | ] 71 | ) 72 | fun selectMany(selectStatement: SelectStatementProvider): List 73 | 74 | @SelectProvider(type = SqlProviderAdapter::class, method = "select") 75 | @ResultMap("GeneratedAlwaysResult") 76 | fun selectOne(selectStatement: SelectStatementProvider): GeneratedAlwaysRow? 77 | } 78 | 79 | fun GeneratedAlwaysMapper.count(completer: CountCompleter) = 80 | countFrom(this::count, generatedAlways, completer) 81 | 82 | fun GeneratedAlwaysMapper.delete(completer: DeleteCompleter) = 83 | deleteFrom(this::delete, generatedAlways, completer) 84 | 85 | fun GeneratedAlwaysMapper.deleteByPrimaryKey(id_: Int) = 86 | delete { 87 | where { id isEqualTo id_ } 88 | } 89 | 90 | fun GeneratedAlwaysMapper.insert(row: GeneratedAlwaysRow) = 91 | insert( 92 | this::insert, 93 | row, 94 | generatedAlways 95 | ) { 96 | map(firstName) toProperty "firstName" 97 | map(lastName) toProperty "lastName" 98 | } 99 | 100 | fun GeneratedAlwaysMapper.insertBatch(vararg records: GeneratedAlwaysRow) = 101 | insertBatch(records.toList()) 102 | 103 | fun GeneratedAlwaysMapper.insertBatch(records: List) = 104 | insertBatch( 105 | this::insert, 106 | records, 107 | generatedAlways 108 | ) { 109 | map(firstName) toProperty "firstName" 110 | map(lastName) toProperty "lastName" 111 | } 112 | 113 | fun GeneratedAlwaysMapper.insertMultiple(vararg records: GeneratedAlwaysRow) = 114 | insertMultiple(records.toList()) 115 | 116 | fun GeneratedAlwaysMapper.insertMultiple(records: List) = 117 | insertMultipleWithGeneratedKeys( 118 | this::insertMultiple, 119 | records, 120 | generatedAlways 121 | ) { 122 | map(firstName) toProperty "firstName" 123 | map(lastName) toProperty "lastName" 124 | } 125 | 126 | private val columnList = listOf( 127 | id, 128 | firstName, 129 | lastName, 130 | fullName 131 | ) 132 | 133 | fun GeneratedAlwaysMapper.selectOne(completer: SelectCompleter) = 134 | selectOne( 135 | this::selectOne, 136 | columnList, 137 | generatedAlways, 138 | completer 139 | ) 140 | 141 | fun GeneratedAlwaysMapper.select(completer: SelectCompleter) = 142 | selectList(this::selectMany, columnList, generatedAlways, completer) 143 | 144 | fun GeneratedAlwaysMapper.selectDistinct(completer: SelectCompleter) = 145 | selectDistinct( 146 | this::selectMany, 147 | columnList, 148 | generatedAlways, 149 | completer 150 | ) 151 | 152 | fun GeneratedAlwaysMapper.selectByPrimaryKey(id_: Int) = 153 | selectOne { 154 | where { id isEqualTo id_ } 155 | } 156 | 157 | fun GeneratedAlwaysMapper.update(completer: UpdateCompleter) = 158 | update( 159 | this::update, 160 | generatedAlways, 161 | completer 162 | ) 163 | 164 | fun GeneratedAlwaysMapper.updateByPrimaryKey(row: GeneratedAlwaysRow) = 165 | update { 166 | set(firstName) equalToOrNull row::firstName 167 | set(lastName) equalToOrNull row::lastName 168 | where { id isEqualTo row.id!! } 169 | } 170 | 171 | fun GeneratedAlwaysMapper.updateByPrimaryKeySelective(row: GeneratedAlwaysRow) = 172 | update { 173 | set(firstName) equalToWhenPresent row::firstName 174 | set(lastName) equalToWhenPresent row::lastName 175 | where { id isEqualTo row.id!! } 176 | } 177 | 178 | fun KotlinUpdateBuilder.updateAllColumns(row: GeneratedAlwaysRow) = 179 | apply { 180 | set(firstName) equalToOrNull row::firstName 181 | set(lastName) equalToOrNull row::lastName 182 | } 183 | 184 | fun KotlinUpdateBuilder.updateSelectiveColumns(row: GeneratedAlwaysRow) = 185 | apply { 186 | set(firstName) equalToWhenPresent row::firstName 187 | set(lastName) equalToWhenPresent row::lastName 188 | } 189 | -------------------------------------------------------------------------------- /src/main/kotlin/example06/GeneratedAlwaysRow.kt: -------------------------------------------------------------------------------- 1 | package example06 2 | 3 | data class GeneratedAlwaysRow( 4 | val id: Int? = null, 5 | val firstName: String? = null, 6 | val lastName: String? = null, 7 | val fullName: String? = null 8 | ) 9 | -------------------------------------------------------------------------------- /src/main/kotlin/util/MatchesAny.kt: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import org.mybatis.dynamic.sql.AbstractSubselectCondition 4 | import org.mybatis.dynamic.sql.BindableColumn 5 | import org.mybatis.dynamic.sql.select.SelectModel 6 | import org.mybatis.dynamic.sql.util.Buildable 7 | import org.mybatis.dynamic.sql.util.kotlin.GroupingCriteriaCollector 8 | import org.mybatis.dynamic.sql.util.kotlin.KotlinSubQueryBuilder 9 | 10 | class MatchesAny(selectModelBuilder: Buildable) : AbstractSubselectCondition(selectModelBuilder){ 11 | override fun operator() = "= any" 12 | } 13 | 14 | // The class and function in this file show how to extend the WHERE DSL 15 | 16 | // This should eventually be easier when Kotlin introduces Context Parameters 17 | // https://github.com/Kotlin/KEEP/blob/context-parameters/proposals/context-parameters.md 18 | 19 | fun BindableColumn.matchesAny( 20 | collector: GroupingCriteriaCollector, 21 | subQueryBuilder: KotlinSubQueryBuilder.() -> Unit 22 | ) = 23 | with(collector) { 24 | invoke(MatchesAny(KotlinSubQueryBuilder().apply(subQueryBuilder))) 25 | } 26 | 27 | 28 | // The following shows how to do it with the deprecated Context Receivers method 29 | // We keep this as reference to show a desired future state once Kotlin has a good solution to the 30 | // problem of multiple contexts. This required use of the compiler flag -Xcontext-receivers 31 | 32 | //context (GroupingCriteriaCollector) 33 | //infix fun BindableColumn.matchesAny(subQueryBuilder: KotlinSubQueryBuilder.() -> Unit) = 34 | // invoke(MatchesAny(KotlinSubQueryBuilder().apply(subQueryBuilder))) 35 | -------------------------------------------------------------------------------- /src/main/kotlin/util/YesNoTypeHandler.kt: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import org.apache.ibatis.type.JdbcType 4 | import org.apache.ibatis.type.MappedJdbcTypes 5 | import org.apache.ibatis.type.MappedTypes 6 | import org.apache.ibatis.type.TypeHandler 7 | 8 | import java.sql.CallableStatement 9 | import java.sql.PreparedStatement 10 | import java.sql.ResultSet 11 | 12 | @MappedTypes(Boolean::class) 13 | @MappedJdbcTypes(JdbcType.VARCHAR) 14 | class YesNoTypeHandler : TypeHandler { 15 | 16 | override fun setParameter(ps: PreparedStatement, i: Int, parameter: Boolean, jdbcType: JdbcType) { 17 | ps.setString(i, if (parameter) "Yes" else "No") 18 | } 19 | 20 | override fun getResult(rs: ResultSet, columnName: String): Boolean { 21 | return "Yes" == rs.getString(columnName) 22 | } 23 | 24 | override fun getResult(rs: ResultSet, columnIndex: Int): Boolean { 25 | return "Yes" == rs.getString(columnIndex) 26 | } 27 | 28 | override fun getResult(cs: CallableStatement, columnIndex: Int): Boolean { 29 | return "Yes" == cs.getString(columnIndex) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/kotlin/example01/Example01Test.kt: -------------------------------------------------------------------------------- 1 | package example01 2 | 3 | import org.assertj.core.api.Assertions.* 4 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 5 | import org.apache.ibatis.jdbc.ScriptRunner 6 | import org.apache.ibatis.mapping.Environment 7 | import org.apache.ibatis.session.Configuration 8 | import org.apache.ibatis.session.SqlSession 9 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 10 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 11 | import org.junit.jupiter.api.Test 12 | import java.io.InputStreamReader 13 | import java.sql.DriverManager 14 | import java.time.LocalDate 15 | 16 | class Example01Test { 17 | private fun newSession(): SqlSession { 18 | Class.forName(JDBC_DRIVER) 19 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 20 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 21 | val sr = ScriptRunner(connection) 22 | sr.setLogWriter(null) 23 | sr.runScript(InputStreamReader(script!!)) 24 | } 25 | 26 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 27 | val environment = Environment("test", JdbcTransactionFactory(), ds) 28 | val config = Configuration(environment) 29 | config.addMapper(Example01Mapper::class.java) 30 | return SqlSessionFactoryBuilder().build(config).openSession() 31 | } 32 | 33 | @Test 34 | fun selectPersonWithAllFields() { 35 | newSession().use { session -> 36 | val mapper = session.getMapper(Example01Mapper::class.java) 37 | 38 | val person = mapper.selectPersonById(1) 39 | 40 | assertThat(person.id).isEqualTo(1) 41 | assertThat(person.firstName).isEqualTo("Fred") 42 | assertThat(person.lastName).isEqualTo("Flintstone") 43 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1935, 2, 1)) 44 | assertThat(person.employed).isEqualToIgnoringCase("Yes") 45 | assertThat(person.occupation).isEqualTo("Brontosaurus Operator") 46 | } 47 | } 48 | 49 | @Test 50 | fun selectPersonWithNullOccupation() { 51 | newSession().use { session -> 52 | val mapper = session.getMapper(Example01Mapper::class.java) 53 | 54 | val person = mapper.selectPersonById(3) 55 | 56 | assertThat(person.id).isEqualTo(3) 57 | assertThat(person.firstName).isEqualTo("Pebbles") 58 | assertThat(person.lastName).isEqualTo("Flintstone") 59 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 60 | assertThat(person.employed).isEqualToIgnoringCase("No") 61 | assertThat(person.occupation).isNull() 62 | } 63 | } 64 | 65 | @Test 66 | fun selectPersonWithNullOccupationAndElvisOperator() { 67 | newSession().use { session -> 68 | val mapper = session.getMapper(Example01Mapper::class.java) 69 | 70 | val person = mapper.selectPersonById(3) 71 | 72 | assertThat(person.id).isEqualTo(3) 73 | assertThat(person.firstName).isEqualTo("Pebbles") 74 | assertThat(person.lastName).isEqualTo("Flintstone") 75 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 76 | assertThat(person.employed).isEqualToIgnoringCase("No") 77 | assertThat(person.occupation ?: "").isEqualTo("") 78 | } 79 | } 80 | 81 | companion object { 82 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 83 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/kotlin/example02/Example02Test.kt: -------------------------------------------------------------------------------- 1 | package example02 2 | 3 | import org.assertj.core.api.Assertions.* 4 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 5 | import org.apache.ibatis.jdbc.ScriptRunner 6 | import org.apache.ibatis.mapping.Environment 7 | import org.apache.ibatis.session.Configuration 8 | import org.apache.ibatis.session.SqlSession 9 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 10 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 11 | import org.junit.jupiter.api.Test 12 | import util.YesNoTypeHandler 13 | import java.io.InputStreamReader 14 | import java.sql.DriverManager 15 | import java.time.LocalDate 16 | 17 | class Example02Test { 18 | private fun newSession(): SqlSession { 19 | Class.forName(JDBC_DRIVER) 20 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 21 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 22 | val sr = ScriptRunner(connection) 23 | sr.setLogWriter(null) 24 | sr.runScript(InputStreamReader(script!!)) 25 | } 26 | 27 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 28 | val environment = Environment("test", JdbcTransactionFactory(), ds) 29 | val config = Configuration(environment) 30 | // register the type handler... 31 | config.typeHandlerRegistry.register(YesNoTypeHandler::class.java) 32 | config.addMapper(Example02Mapper::class.java) 33 | return SqlSessionFactoryBuilder().build(config).openSession() 34 | } 35 | 36 | @Test 37 | fun selectPersonWithAllFields() { 38 | newSession().use { session -> 39 | val mapper = session.getMapper(Example02Mapper::class.java) 40 | 41 | val person = mapper.selectPersonById(1) 42 | 43 | assertThat(person.id).isEqualTo(1) 44 | assertThat(person.firstName).isEqualTo("Fred") 45 | assertThat(person.lastName).isEqualTo("Flintstone") 46 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1935, 2, 1)) 47 | assertThat(person.employed).isTrue 48 | assertThat(person.occupation).isEqualTo("Brontosaurus Operator") 49 | } 50 | } 51 | 52 | @Test 53 | fun selectPersonWithNullOccupation() { 54 | newSession().use { session -> 55 | val mapper = session.getMapper(Example02Mapper::class.java) 56 | 57 | val person = mapper.selectPersonById(3) 58 | 59 | assertThat(person.id).isEqualTo(3) 60 | assertThat(person.firstName).isEqualTo("Pebbles") 61 | assertThat(person.lastName).isEqualTo("Flintstone") 62 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 63 | assertThat(person.employed).isFalse 64 | assertThat(person.occupation).isNull() 65 | } 66 | } 67 | 68 | @Test 69 | fun selectPersonWithNullOccupationAndElvisOperator() { 70 | newSession().use { session -> 71 | val mapper = session.getMapper(Example02Mapper::class.java) 72 | 73 | val person = mapper.selectPersonById(3) 74 | 75 | assertThat(person.id).isEqualTo(3) 76 | assertThat(person.firstName).isEqualTo("Pebbles") 77 | assertThat(person.lastName).isEqualTo("Flintstone") 78 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 79 | assertThat(person.employed).isFalse 80 | assertThat(person.occupation ?: "").isEqualTo("") 81 | } 82 | } 83 | 84 | companion object { 85 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 86 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/kotlin/example02/oldmybatis/Example02OldMyBatisTest.kt: -------------------------------------------------------------------------------- 1 | package example02.oldmybatis 2 | 3 | import org.assertj.core.api.Assertions.* 4 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 5 | import org.apache.ibatis.jdbc.ScriptRunner 6 | import org.apache.ibatis.mapping.Environment 7 | import org.apache.ibatis.session.Configuration 8 | import org.apache.ibatis.session.SqlSession 9 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 10 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 11 | import org.junit.jupiter.api.Test 12 | import util.YesNoTypeHandler 13 | import java.io.InputStreamReader 14 | import java.sql.DriverManager 15 | import java.time.LocalDate 16 | import java.time.ZoneId 17 | import java.util.* 18 | 19 | class Example02OldMyBatisTest { 20 | private fun newSession(): SqlSession { 21 | Class.forName(JDBC_DRIVER) 22 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 23 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 24 | val sr = ScriptRunner(connection) 25 | sr.setLogWriter(null) 26 | sr.runScript(InputStreamReader(script!!)) 27 | } 28 | 29 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 30 | val environment = Environment("test", JdbcTransactionFactory(), ds) 31 | val config = Configuration(environment) 32 | // register the type handler... 33 | config.typeHandlerRegistry.register(YesNoTypeHandler::class.java) 34 | config.addMapper(Example02OldMyBatisMapper::class.java) 35 | return SqlSessionFactoryBuilder().build(config).openSession() 36 | } 37 | 38 | @Test 39 | fun selectPersonWithAllFields() { 40 | newSession().use { session -> 41 | val mapper = session.getMapper(Example02OldMyBatisMapper::class.java) 42 | 43 | val person = mapper.selectPersonById(1) 44 | 45 | assertThat(person.id).isEqualTo(1) 46 | assertThat(person.firstName).isEqualTo("Fred") 47 | assertThat(person.lastName).isEqualTo("Flintstone") 48 | assertThat(person.birthDate).isEqualTo(Date.from(LocalDate.of(1935, 2, 1).atStartOfDay(ZoneId.systemDefault()).toInstant())) 49 | assertThat(person.employed).isTrue 50 | assertThat(person.occupation).isEqualTo("Brontosaurus Operator") 51 | } 52 | } 53 | 54 | @Test 55 | fun selectPersonWithNullOccupation() { 56 | newSession().use { session -> 57 | val mapper = session.getMapper(Example02OldMyBatisMapper::class.java) 58 | 59 | val person = mapper.selectPersonById(3) 60 | 61 | assertThat(person.id).isEqualTo(3) 62 | assertThat(person.firstName).isEqualTo("Pebbles") 63 | assertThat(person.lastName).isEqualTo("Flintstone") 64 | assertThat(person.birthDate).isEqualTo(Date.from(LocalDate.of(1960, 5, 6).atStartOfDay(ZoneId.systemDefault()).toInstant())) 65 | assertThat(person.employed).isFalse 66 | assertThat(person.occupation).isNull() 67 | } 68 | } 69 | 70 | @Test 71 | fun selectPersonWithNullOccupationAndElvisOperator() { 72 | newSession().use { session -> 73 | val mapper = session.getMapper(Example02OldMyBatisMapper::class.java) 74 | 75 | val person = mapper.selectPersonById(3) 76 | 77 | assertThat(person.id).isEqualTo(3) 78 | assertThat(person.firstName).isEqualTo("Pebbles") 79 | assertThat(person.lastName).isEqualTo("Flintstone") 80 | assertThat(person.birthDate).isEqualTo(Date.from(LocalDate.of(1960, 5, 6).atStartOfDay(ZoneId.systemDefault()).toInstant())) 81 | assertThat(person.employed).isFalse 82 | assertThat(person.occupation ?: "").isEqualTo("") 83 | } 84 | } 85 | 86 | companion object { 87 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 88 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/test/kotlin/example03/Example03Test.kt: -------------------------------------------------------------------------------- 1 | package example03 2 | 3 | import org.assertj.core.api.Assertions.* 4 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 5 | import org.apache.ibatis.jdbc.ScriptRunner 6 | import org.apache.ibatis.mapping.Environment 7 | import org.apache.ibatis.session.Configuration 8 | import org.apache.ibatis.session.SqlSession 9 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 10 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 11 | import org.junit.jupiter.api.Test 12 | import java.io.InputStreamReader 13 | import java.sql.DriverManager 14 | import java.time.LocalDate 15 | 16 | class Example03Test { 17 | private fun newSession(): SqlSession { 18 | Class.forName(JDBC_DRIVER) 19 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 20 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 21 | val sr = ScriptRunner(connection) 22 | sr.setLogWriter(null) 23 | sr.runScript(InputStreamReader(script!!)) 24 | } 25 | 26 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 27 | val environment = Environment("test", JdbcTransactionFactory(), ds) 28 | val config = Configuration(environment) 29 | config.addMapper(Example03Mapper::class.java) 30 | return SqlSessionFactoryBuilder().build(config).openSession() 31 | } 32 | 33 | @Test 34 | fun selectPersonWithAllFields() { 35 | newSession().use { session -> 36 | val mapper = session.getMapper(Example03Mapper::class.java) 37 | 38 | val person = mapper.selectPersonById(1) 39 | 40 | assertThat(person.id).isEqualTo(1) 41 | assertThat(person.firstName).isEqualTo("Fred") 42 | assertThat(person.lastName).isEqualTo("Flintstone") 43 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1935, 2, 1)) 44 | assertThat(person.employed).isTrue 45 | assertThat(person.occupation).isEqualTo("Brontosaurus Operator") 46 | assertThat(person.address.id).isEqualTo(1) 47 | assertThat(person.address.streetAddress).isEqualTo("123 Main Street") 48 | assertThat(person.address.city).isEqualTo("Bedrock") 49 | assertThat(person.address.state).isEqualTo("IN") 50 | } 51 | } 52 | 53 | @Test 54 | fun selectPersonWithNullOccupation() { 55 | newSession().use { session -> 56 | val mapper = session.getMapper(Example03Mapper::class.java) 57 | 58 | val person = mapper.selectPersonById(3) 59 | 60 | assertThat(person.id).isEqualTo(3) 61 | assertThat(person.firstName).isEqualTo("Pebbles") 62 | assertThat(person.lastName).isEqualTo("Flintstone") 63 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 64 | assertThat(person.employed).isFalse 65 | assertThat(person.occupation).isNull() 66 | assertThat(person.address.id).isEqualTo(1) 67 | assertThat(person.address.streetAddress).isEqualTo("123 Main Street") 68 | assertThat(person.address.city).isEqualTo("Bedrock") 69 | assertThat(person.address.state).isEqualTo("IN") 70 | } 71 | } 72 | 73 | @Test 74 | fun selectPersonWithNullOccupationAndElvisOperator() { 75 | newSession().use { session -> 76 | val mapper = session.getMapper(Example03Mapper::class.java) 77 | 78 | val person = mapper.selectPersonById(3) 79 | 80 | assertThat(person.id).isEqualTo(3) 81 | assertThat(person.firstName).isEqualTo("Pebbles") 82 | assertThat(person.lastName).isEqualTo("Flintstone") 83 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 84 | assertThat(person.employed).isFalse 85 | assertThat(person.occupation ?: "").isEqualTo("") 86 | assertThat(person.address.id).isEqualTo(1) 87 | assertThat(person.address.streetAddress).isEqualTo("123 Main Street") 88 | assertThat(person.address.city).isEqualTo("Bedrock") 89 | assertThat(person.address.state).isEqualTo("IN") 90 | } 91 | } 92 | 93 | companion object { 94 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 95 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/kotlin/example04/Example04Test.kt: -------------------------------------------------------------------------------- 1 | package example04 2 | 3 | import org.assertj.core.api.Assertions.* 4 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 5 | import org.apache.ibatis.jdbc.ScriptRunner 6 | import org.apache.ibatis.mapping.Environment 7 | import org.apache.ibatis.session.Configuration 8 | import org.apache.ibatis.session.SqlSession 9 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 10 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 11 | import org.junit.jupiter.api.Test 12 | import java.io.InputStreamReader 13 | import java.sql.DriverManager 14 | import java.time.LocalDate 15 | 16 | class Example04Test { 17 | private fun newSession(): SqlSession { 18 | Class.forName(JDBC_DRIVER) 19 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 20 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 21 | val sr = ScriptRunner(connection) 22 | sr.setLogWriter(null) 23 | sr.runScript(InputStreamReader(script!!)) 24 | } 25 | 26 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 27 | val environment = Environment("test", JdbcTransactionFactory(), ds) 28 | val config = Configuration(environment) 29 | config.addMapper(Example04Mapper::class.java) 30 | return SqlSessionFactoryBuilder().build(config).openSession() 31 | } 32 | 33 | @Test 34 | fun selectAddressById() { 35 | newSession().use { session -> 36 | val mapper = session.getMapper(Example04Mapper::class.java) 37 | 38 | val address = mapper.selectAddressById(1) 39 | 40 | assertThat(address.id).isEqualTo(1) 41 | assertThat(address.streetAddress).isEqualTo("123 Main Street") 42 | assertThat(address.city).isEqualTo("Bedrock") 43 | assertThat(address.state).isEqualTo("IN") 44 | 45 | assertThat(address.people.size).isEqualTo(3) 46 | 47 | assertThat(address.people[0].firstName).isEqualTo("Fred") 48 | assertThat(address.people[0].lastName).isEqualTo("Flintstone") 49 | assertThat(address.people[0].birthDate).isEqualTo(LocalDate.of(1935, 2, 1)) 50 | assertThat(address.people[0].employed).isTrue 51 | assertThat(address.people[0].occupation).isEqualTo("Brontosaurus Operator") 52 | 53 | assertThat(address.people[1].firstName).isEqualTo("Wilma") 54 | assertThat(address.people[1].lastName).isEqualTo("Flintstone") 55 | assertThat(address.people[1].birthDate).isEqualTo(LocalDate.of(1940, 2, 1)) 56 | assertThat(address.people[1].employed).isTrue 57 | assertThat(address.people[1].occupation).isEqualTo("Accountant") 58 | 59 | assertThat(address.people[2].firstName).isEqualTo("Pebbles") 60 | assertThat(address.people[2].lastName).isEqualTo("Flintstone") 61 | assertThat(address.people[2].birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 62 | assertThat(address.people[2].employed).isFalse 63 | assertThat(address.people[2].occupation).isNull() 64 | } 65 | } 66 | 67 | companion object { 68 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 69 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/test/kotlin/example04/lazy/Example04LazyTest.kt: -------------------------------------------------------------------------------- 1 | package example04.lazy 2 | 3 | import org.assertj.core.api.Assertions.* 4 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 5 | import org.apache.ibatis.jdbc.ScriptRunner 6 | import org.apache.ibatis.mapping.Environment 7 | import org.apache.ibatis.session.Configuration 8 | import org.apache.ibatis.session.SqlSession 9 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 10 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 11 | import org.junit.jupiter.api.Test 12 | import java.io.InputStreamReader 13 | import java.sql.DriverManager 14 | import java.time.LocalDate 15 | 16 | class Example04LazyTest { 17 | private fun newSession(): SqlSession { 18 | Class.forName(JDBC_DRIVER) 19 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 20 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 21 | val sr = ScriptRunner(connection) 22 | sr.setLogWriter(null) 23 | sr.runScript(InputStreamReader(script!!)) 24 | } 25 | 26 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 27 | val environment = Environment("test", JdbcTransactionFactory(), ds) 28 | val config = Configuration(environment) 29 | config.addMapper(Example04LazyMapper::class.java) 30 | return SqlSessionFactoryBuilder().build(config).openSession() 31 | } 32 | 33 | @Test 34 | fun selectAddressByIdForcingLazyLoad() { 35 | newSession().use { session -> 36 | val mapper = session.getMapper(Example04LazyMapper::class.java) 37 | 38 | val address = mapper.selectAddressById(1) 39 | 40 | assertThat(address.id).isEqualTo(1) 41 | assertThat(address.streetAddress).isEqualTo("123 Main Street") 42 | assertThat(address.city).isEqualTo("Bedrock") 43 | assertThat(address.state).isEqualTo("IN") 44 | 45 | assertThat(address.people.size).isEqualTo(3) 46 | 47 | assertThat(address.people[0].firstName).isEqualTo("Fred") 48 | assertThat(address.people[0].lastName).isEqualTo("Flintstone") 49 | assertThat(address.people[0].birthDate).isEqualTo(LocalDate.of(1935, 2, 1)) 50 | assertThat(address.people[0].employed).isTrue 51 | assertThat(address.people[0].occupation).isEqualTo("Brontosaurus Operator") 52 | 53 | assertThat(address.people[1].firstName).isEqualTo("Wilma") 54 | assertThat(address.people[1].lastName).isEqualTo("Flintstone") 55 | assertThat(address.people[1].birthDate).isEqualTo(LocalDate.of(1940, 2, 1)) 56 | assertThat(address.people[1].employed).isTrue 57 | assertThat(address.people[1].occupation).isEqualTo("Accountant") 58 | 59 | assertThat(address.people[2].firstName).isEqualTo("Pebbles") 60 | assertThat(address.people[2].lastName).isEqualTo("Flintstone") 61 | assertThat(address.people[2].birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 62 | assertThat(address.people[2].employed).isFalse 63 | assertThat(address.people[2].occupation).isNull() 64 | } 65 | } 66 | 67 | companion object { 68 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 69 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/test/kotlin/example05/Example05Test.kt: -------------------------------------------------------------------------------- 1 | package example05 2 | 3 | import example05.PersonDynamicSqlSupport.employed 4 | import example05.PersonDynamicSqlSupport.firstName 5 | import example05.PersonDynamicSqlSupport.id 6 | import example05.PersonDynamicSqlSupport.lastName 7 | import example05.PersonDynamicSqlSupport.occupation 8 | import example05.PersonDynamicSqlSupport.parentId 9 | import example05.PersonDynamicSqlSupport.person 10 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 11 | import org.apache.ibatis.jdbc.ScriptRunner 12 | import org.apache.ibatis.mapping.Environment 13 | import org.apache.ibatis.session.Configuration 14 | import org.apache.ibatis.session.ExecutorType 15 | import org.apache.ibatis.session.SqlSession 16 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 17 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 18 | import org.assertj.core.api.Assertions.assertThat 19 | import org.junit.jupiter.api.Test 20 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.select 21 | import org.mybatis.dynamic.sql.util.mybatis3.CommonSelectMapper 22 | import util.YesNoTypeHandler 23 | import util.matchesAny 24 | import java.io.InputStreamReader 25 | import java.sql.DriverManager 26 | import java.time.LocalDate 27 | 28 | internal class Example05Test { 29 | 30 | private fun newSession(executorType: ExecutorType = ExecutorType.REUSE): SqlSession { 31 | Class.forName(JDBC_DRIVER) 32 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 33 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 34 | val sr = ScriptRunner(connection) 35 | sr.setLogWriter(null) 36 | sr.runScript(InputStreamReader(script!!)) 37 | } 38 | 39 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 40 | val environment = Environment("test", JdbcTransactionFactory(), ds) 41 | val config = Configuration(environment) 42 | config.typeHandlerRegistry.register(YesNoTypeHandler::class.java) 43 | config.addMapper(PersonMapper::class.java) 44 | config.addMapper(CommonSelectMapper::class.java) 45 | return SqlSessionFactoryBuilder().build(config).openSession(executorType) 46 | } 47 | 48 | @Test 49 | fun testSelect() { 50 | newSession().use { session -> 51 | val mapper = session.getMapper(PersonMapper::class.java) 52 | 53 | val rows = mapper.select { 54 | where { 55 | id isEqualTo 1 56 | or { occupation.isNull() } 57 | } 58 | orderBy(id) 59 | } 60 | 61 | assertThat(rows.size).isEqualTo(3) 62 | assertThat(rows[0].id).isEqualTo(1) 63 | assertThat(rows[0].firstName).isEqualTo("Fred") 64 | assertThat(rows[0].lastName).isEqualTo("Flintstone") 65 | assertThat(rows[0].birthDate).isNotNull 66 | assertThat(rows[0].employed).isTrue 67 | assertThat(rows[0].occupation).isEqualTo("Brontosaurus Operator") 68 | assertThat(rows[0].addressId).isEqualTo(1) 69 | assertThat(rows[0].parentId).isNull() 70 | } 71 | } 72 | 73 | @Test 74 | fun testSelectAllRows() { 75 | newSession().use { session -> 76 | val mapper = session.getMapper(PersonMapper::class.java) 77 | 78 | val rows = mapper.select { allRows() } 79 | 80 | assertThat(rows.size).isEqualTo(6) 81 | } 82 | } 83 | 84 | @Test 85 | fun testSelectAllRowsWithOrder() { 86 | newSession().use { session -> 87 | val mapper = session.getMapper(PersonMapper::class.java) 88 | 89 | val rows = mapper.select { 90 | allRows() 91 | orderBy(firstName, lastName) 92 | } 93 | 94 | assertThat(rows.size).isEqualTo(6) 95 | assertThat(rows[0].firstName).isEqualTo("Bamm Bamm") 96 | } 97 | } 98 | 99 | @Test 100 | fun testSelectByPrimaryKeyNoRecord() { 101 | newSession().use { session -> 102 | val mapper = session.getMapper(PersonMapper::class.java) 103 | 104 | val row = mapper.selectByPrimaryKey(22) 105 | 106 | assertThat(row?.id).isNull() 107 | assertThat(row).isNull() 108 | } 109 | } 110 | 111 | @Test 112 | fun testSelectDistinct() { 113 | newSession().use { session -> 114 | val mapper = session.getMapper(PersonMapper::class.java) 115 | 116 | val rows = mapper.selectDistinct { 117 | where { 118 | id isGreaterThan 1 119 | or { occupation.isNull() } 120 | } 121 | } 122 | 123 | assertThat(rows.size).isEqualTo(5) 124 | } 125 | } 126 | 127 | @Test 128 | fun testSelectWithTypeHandler() { 129 | newSession().use { session -> 130 | val mapper = session.getMapper(PersonMapper::class.java) 131 | 132 | val rows = mapper.select { 133 | where { employed isEqualTo false } 134 | orderBy(id) 135 | } 136 | 137 | assertThat(rows.size).isEqualTo(2) 138 | assertThat(rows[0].id).isEqualTo(3) 139 | assertThat(rows[1].id).isEqualTo(6) 140 | } 141 | } 142 | 143 | @Test 144 | fun testFirstNameIn() { 145 | newSession().use { session -> 146 | val mapper = session.getMapper(PersonMapper::class.java) 147 | 148 | val rows = mapper.select { where { firstName.isIn("Fred", "Barney") } } 149 | 150 | assertThat(rows.size).isEqualTo(2) 151 | assertThat(rows[0].lastName).isEqualTo("Flintstone") 152 | assertThat(rows[1].lastName).isEqualTo("Rubble") 153 | } 154 | } 155 | 156 | @Test 157 | fun testDelete() { 158 | newSession().use { session -> 159 | val mapper = session.getMapper(PersonMapper::class.java) 160 | val rows = mapper.delete { where { occupation.isNull() } } 161 | assertThat(rows).isEqualTo(2) 162 | } 163 | } 164 | 165 | @Test 166 | fun testDeleteAllRows() { 167 | newSession().use { session -> 168 | val mapper = session.getMapper(PersonMapper::class.java) 169 | val rows = mapper.delete { allRows() } 170 | assertThat(rows).isEqualTo(6) 171 | } 172 | } 173 | 174 | @Test 175 | fun testDeleteByPrimaryKey() { 176 | newSession().use { session -> 177 | val mapper = session.getMapper(PersonMapper::class.java) 178 | val rows = mapper.deleteByPrimaryKey(2) 179 | 180 | assertThat(rows).isEqualTo(1) 181 | } 182 | } 183 | 184 | @Test 185 | fun testInsert() { 186 | newSession().use { session -> 187 | val mapper = session.getMapper(PersonMapper::class.java) 188 | val record = PersonRecord(10, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 189 | 190 | val rows = mapper.insert(record) 191 | assertThat(rows).isEqualTo(1) 192 | } 193 | } 194 | 195 | @Test 196 | fun testInsertMultiple() { 197 | newSession().use { session -> 198 | val mapper = session.getMapper(PersonMapper::class.java) 199 | 200 | val rows = mapper.insertMultiple( 201 | PersonRecord(10, "Joe", "Jones", LocalDate.now(), true, "Developer", 22), 202 | PersonRecord(11, "Sam", "Smith", LocalDate.now(), true, "Architect", 23) 203 | ) 204 | assertThat(rows).isEqualTo(2) 205 | } 206 | } 207 | 208 | @Test 209 | fun testInsertBatch() { 210 | newSession(ExecutorType.BATCH).use { session -> 211 | val mapper = session.getMapper(PersonMapper::class.java) 212 | 213 | mapper.insertBatch( 214 | PersonRecord(10, "Joe", "Jones", LocalDate.now(), true, "Developer", 22), 215 | PersonRecord(11, "Sam", "Smith", LocalDate.now(), true, "Architect", 23) 216 | ) 217 | 218 | val batchResults = mapper.flush() 219 | assertThat(batchResults).hasSize(1) 220 | assertThat(batchResults.flatMap { it.updateCounts.asList() }.sum()).isEqualTo(2) 221 | } 222 | } 223 | 224 | @Test 225 | fun testInsertWithNull() { 226 | newSession().use { session -> 227 | val mapper = session.getMapper(PersonMapper::class.java) 228 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), false, null, 22) 229 | 230 | val rows = mapper.insert(record) 231 | assertThat(rows).isEqualTo(1) 232 | } 233 | } 234 | 235 | @Test 236 | fun testUpdateByPrimaryKey() { 237 | newSession().use { session -> 238 | val mapper = session.getMapper(PersonMapper::class.java) 239 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 240 | 241 | var rows = mapper.insert(record) 242 | assertThat(rows).isEqualTo(1) 243 | 244 | val updateRecord = record.copy(occupation = "Programmer") 245 | rows = mapper.updateByPrimaryKey(updateRecord) 246 | assertThat(rows).isEqualTo(1) 247 | 248 | val newRecord = mapper.selectByPrimaryKey(100) 249 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 250 | } 251 | } 252 | 253 | @Test 254 | fun testUpdateByPrimaryKeySelective() { 255 | newSession().use { session -> 256 | val mapper = session.getMapper(PersonMapper::class.java) 257 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 258 | 259 | var rows = mapper.insert(record) 260 | assertThat(rows).isEqualTo(1) 261 | 262 | val updateRecord = PersonRecord(id = 100, occupation = "Programmer") 263 | rows = mapper.updateByPrimaryKeySelective(updateRecord) 264 | assertThat(rows).isEqualTo(1) 265 | 266 | val newRecord = mapper.selectByPrimaryKey(100) 267 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 268 | assertThat(newRecord?.firstName).isEqualTo("Joe") 269 | 270 | } 271 | } 272 | 273 | @Test 274 | fun testUpdateByPrimaryKeySelectiveWithCopy() { 275 | newSession().use { session -> 276 | val mapper = session.getMapper(PersonMapper::class.java) 277 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 278 | 279 | var rows = mapper.insert(record) 280 | assertThat(rows).isEqualTo(1) 281 | 282 | val updateRecord = record.copy(occupation = "Programmer") 283 | rows = mapper.updateByPrimaryKeySelective(updateRecord) 284 | assertThat(rows).isEqualTo(1) 285 | 286 | val newRecord = mapper.selectByPrimaryKey(100) 287 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 288 | assertThat(newRecord?.firstName).isEqualTo("Joe") 289 | } 290 | } 291 | 292 | @Test 293 | fun testUpdateWithNulls() { 294 | newSession().use { session -> 295 | val mapper = session.getMapper(PersonMapper::class.java) 296 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 297 | 298 | var rows = mapper.insert(record) 299 | assertThat(rows).isEqualTo(1) 300 | 301 | rows = mapper.update { 302 | set(occupation).equalToNull() 303 | set(employed).equalTo(false) 304 | where { id isEqualTo 100 } 305 | } 306 | 307 | assertThat(rows).isEqualTo(1) 308 | 309 | val newRecord = mapper.selectByPrimaryKey(100) 310 | assertThat(newRecord?.occupation).isNull() 311 | assertThat(newRecord?.employed).isEqualTo(false) 312 | assertThat(newRecord?.firstName).isEqualTo("Joe") 313 | } 314 | } 315 | 316 | @Test 317 | fun testUpdate() { 318 | newSession().use { session -> 319 | val mapper = session.getMapper(PersonMapper::class.java) 320 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 321 | 322 | var rows = mapper.insert(record) 323 | assertThat(rows).isEqualTo(1) 324 | 325 | val updateRecord = record.copy(occupation = "Programmer") 326 | rows = mapper.update { 327 | updateAllColumns(updateRecord) 328 | where { 329 | id isEqualTo 100 330 | and { firstName isEqualTo "Joe" } 331 | } 332 | } 333 | 334 | assertThat(rows).isEqualTo(1) 335 | 336 | val newRecord = mapper.selectByPrimaryKey(100) 337 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 338 | } 339 | } 340 | 341 | @Test 342 | fun testUpdateAllRows() { 343 | newSession().use { session -> 344 | val mapper = session.getMapper(PersonMapper::class.java) 345 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 346 | 347 | var rows = mapper.insert(record) 348 | assertThat(rows).isEqualTo(1) 349 | 350 | val updateRecord = PersonRecord(occupation = "Programmer") 351 | 352 | rows = mapper.update { 353 | updateSelectiveColumns(updateRecord) 354 | } 355 | 356 | assertThat(rows).isEqualTo(7) 357 | 358 | val newRecord = mapper.selectByPrimaryKey(100) 359 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 360 | } 361 | } 362 | 363 | @Test 364 | fun testCount() { 365 | newSession().use { session -> 366 | val mapper = session.getMapper(PersonMapper::class.java) 367 | val rows = mapper.count { where { occupation.isNull() } } 368 | 369 | assertThat(rows).isEqualTo(2L) 370 | } 371 | } 372 | 373 | @Test 374 | fun testCountAll() { 375 | newSession().use { session -> 376 | val mapper = session.getMapper(PersonMapper::class.java) 377 | val rows = mapper.count { allRows() } 378 | 379 | assertThat(rows).isEqualTo(6L) 380 | } 381 | } 382 | 383 | @Test 384 | fun testSelfJoin() { 385 | newSession().use { session -> 386 | val mapper = session.getMapper(CommonSelectMapper::class.java) 387 | 388 | val person2 = PersonDynamicSqlSupport.Person() 389 | 390 | // get Bamm Bamm's parent - should be Barney 391 | val selectStatement = select(id, firstName, parentId) { 392 | from(person, "p1") 393 | join(person2, "p2") on { id isEqualTo person2.parentId} 394 | where { person2.id isEqualTo 6 } 395 | } 396 | 397 | val expectedStatement = ("select p1.id, p1.first_name, p1.parent_id" 398 | + " from Person p1 join Person p2 on p1.id = p2.parent_id" 399 | + " where p2.id = #{parameters.p1,jdbcType=INTEGER}") 400 | assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) 401 | 402 | val row = mapper.selectOneMappedRow(selectStatement) 403 | 404 | assertThat(row).isNotNull 405 | assertThat(row).containsEntry("ID", 4) 406 | assertThat(row).containsEntry("FIRST_NAME", "Barney") 407 | assertThat(row).doesNotContainKey("PARENT_ID") 408 | } 409 | } 410 | 411 | @Test 412 | fun testReceiverFunction() { 413 | newSession().use { session -> 414 | val mapper = session.getMapper(CommonSelectMapper::class.java) 415 | 416 | // find all children with a convoluted query 417 | val selectStatement = select(id, firstName, lastName) { 418 | from(person) 419 | where { 420 | id.matchesAny(this) { 421 | select (id) { 422 | from(person) 423 | where { 424 | parentId.isNotNull() 425 | } 426 | } 427 | } 428 | } 429 | orderBy(id) 430 | } 431 | 432 | val expected = "select id, first_name, last_name from Person " + 433 | "where id = any (select id from Person where parent_id is not null) order by id" 434 | 435 | assertThat(selectStatement.selectStatement).isEqualTo(expected) 436 | 437 | val rows = mapper.selectManyMappedRows(selectStatement) 438 | 439 | assertThat(rows).hasSize(2) 440 | assertThat(rows[0]["FIRST_NAME"]).isEqualTo("Pebbles") 441 | assertThat(rows[1]["FIRST_NAME"]).isEqualTo("Bamm Bamm") 442 | } 443 | } 444 | 445 | companion object { 446 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 447 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 448 | } 449 | } 450 | -------------------------------------------------------------------------------- /src/test/kotlin/example05/StatementConfigurationTest.kt: -------------------------------------------------------------------------------- 1 | package example05 2 | 3 | import example05.PersonDynamicSqlSupport.person 4 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 5 | import org.apache.ibatis.jdbc.ScriptRunner 6 | import org.apache.ibatis.mapping.Environment 7 | import org.apache.ibatis.session.Configuration 8 | import org.apache.ibatis.session.ExecutorType 9 | import org.apache.ibatis.session.SqlSession 10 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 11 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 12 | import org.assertj.core.api.Assertions.assertThat 13 | import org.assertj.core.api.Assertions.assertThatExceptionOfType 14 | import org.junit.jupiter.api.Test 15 | import org.mybatis.dynamic.sql.exception.NonRenderingWhereClauseException 16 | import org.mybatis.dynamic.sql.util.kotlin.elements.isLikeCaseInsensitiveWhenPresent 17 | import org.mybatis.dynamic.sql.util.mybatis3.CommonSelectMapper 18 | import util.YesNoTypeHandler 19 | import java.io.InputStreamReader 20 | import java.sql.DriverManager 21 | 22 | class StatementConfigurationTest { 23 | private fun newSession(executorType: ExecutorType = ExecutorType.REUSE): SqlSession { 24 | Class.forName(Example05Test.JDBC_DRIVER) 25 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 26 | DriverManager.getConnection(Example05Test.JDBC_URL, "sa", "").use { connection -> 27 | val sr = ScriptRunner(connection) 28 | sr.setLogWriter(null) 29 | sr.runScript(InputStreamReader(script!!)) 30 | } 31 | 32 | val ds = UnpooledDataSource(Example05Test.JDBC_DRIVER, Example05Test.JDBC_URL, "sa", "") 33 | val environment = Environment("test", JdbcTransactionFactory(), ds) 34 | val config = Configuration(environment) 35 | config.typeHandlerRegistry.register(YesNoTypeHandler::class.java) 36 | config.addMapper(PersonMapper::class.java) 37 | config.addMapper(CommonSelectMapper::class.java) 38 | return SqlSessionFactoryBuilder().build(config).openSession(executorType) 39 | } 40 | 41 | @Test 42 | fun testSelectAllRows() { 43 | val rows = search(null, null, true) 44 | assertThat(rows.size).isEqualTo(6) 45 | } 46 | 47 | @Test 48 | fun testSelectSomeRowsByFirstName() { 49 | val rows = search("fr", null, false) 50 | assertThat(rows.size).isEqualTo(1) 51 | } 52 | 53 | @Test 54 | fun testSelectSomeRowsByLastName() { 55 | val rows = search(null,"fl", false) 56 | assertThat(rows).hasSize(3) 57 | assertThat(rows.all { (it.lastName!!).startsWith("Ru") }) 58 | } 59 | 60 | @Test 61 | fun testSearchCriteriaRequired() { 62 | assertThatExceptionOfType(NonRenderingWhereClauseException::class.java).isThrownBy { 63 | search(null, null, false) 64 | } 65 | } 66 | 67 | private fun search(firstName: String?, lastName: String?, allowSearchAll: Boolean): List { 68 | fun String.addWildcards() = "%$this%" 69 | 70 | newSession().use { session -> 71 | val mapper = session.getMapper(PersonMapper::class.java) 72 | 73 | return mapper.select { 74 | where { 75 | person.firstName (isLikeCaseInsensitiveWhenPresent(firstName) 76 | .filter{ it.isNotEmpty() } 77 | .map { it.addWildcards() }) 78 | and { 79 | person.lastName (isLikeCaseInsensitiveWhenPresent(lastName) 80 | .filter{ it.isNotEmpty() } 81 | .map { it.addWildcards()}) 82 | } 83 | } 84 | configureStatement { isNonRenderingWhereClauseAllowed = allowSearchAll } 85 | } 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/kotlin/example06/Example06Test.kt: -------------------------------------------------------------------------------- 1 | package example06 2 | 3 | import example06.GeneratedAlwaysDynamicSqlSupport.firstName 4 | import example06.GeneratedAlwaysDynamicSqlSupport.generatedAlways 5 | import example06.GeneratedAlwaysDynamicSqlSupport.id 6 | import example06.GeneratedAlwaysDynamicSqlSupport.lastName 7 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 8 | import org.apache.ibatis.jdbc.ScriptRunner 9 | import org.apache.ibatis.mapping.Environment 10 | import org.apache.ibatis.session.Configuration 11 | import org.apache.ibatis.session.ExecutorType 12 | import org.apache.ibatis.session.SqlSession 13 | import org.apache.ibatis.session.SqlSessionFactoryBuilder 14 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory 15 | import org.assertj.core.api.Assertions.assertThat 16 | import org.junit.jupiter.api.Test 17 | import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertInto 18 | import org.mybatis.dynamic.sql.util.mybatis3.CommonSelectMapper 19 | import java.io.InputStreamReader 20 | import java.sql.DriverManager 21 | 22 | internal class Example06Test { 23 | 24 | private fun newSession(executorType: ExecutorType = ExecutorType.REUSE): SqlSession { 25 | Class.forName(JDBC_DRIVER) 26 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 27 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 28 | val sr = ScriptRunner(connection) 29 | sr.setLogWriter(null) 30 | sr.runScript(InputStreamReader(script!!)) 31 | } 32 | 33 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 34 | val environment = Environment("test", JdbcTransactionFactory(), ds) 35 | val config = Configuration(environment) 36 | config.addMapper(GeneratedAlwaysMapper::class.java) 37 | config.addMapper(CommonSelectMapper::class.java) 38 | return SqlSessionFactoryBuilder().build(config).openSession(executorType) 39 | } 40 | 41 | @Test 42 | fun testSelect() { 43 | newSession().use { session -> 44 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 45 | 46 | val rows = mapper.select { 47 | where { id isEqualTo 22 } 48 | orderBy(id) 49 | } 50 | 51 | assertThat(rows.size).isEqualTo(1) 52 | assertThat(rows[0].id).isEqualTo(22) 53 | assertThat(rows[0].firstName).isEqualTo("Fred") 54 | assertThat(rows[0].lastName).isEqualTo("Flintstone") 55 | assertThat(rows[0].fullName).isEqualTo("Fred Flintstone") 56 | } 57 | } 58 | 59 | @Test 60 | fun testSelectAllRows() { 61 | newSession().use { session -> 62 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 63 | 64 | val rows = mapper.select { allRows() } 65 | 66 | assertThat(rows.size).isEqualTo(4) 67 | } 68 | } 69 | 70 | @Test 71 | fun testSelectAllRowsWithOrder() { 72 | newSession().use { session -> 73 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 74 | 75 | val rows = mapper.select { 76 | allRows() 77 | orderBy(firstName, lastName) 78 | } 79 | 80 | assertThat(rows.size).isEqualTo(4) 81 | assertThat(rows[0].firstName).isEqualTo("Barney") 82 | } 83 | } 84 | 85 | @Test 86 | fun testSelectByPrimaryKeyNoRecord() { 87 | newSession().use { session -> 88 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 89 | 90 | val row = mapper.selectByPrimaryKey(106) 91 | 92 | assertThat(row).isNull() 93 | } 94 | } 95 | 96 | @Test 97 | fun testSelectDistinct() { 98 | newSession().use { session -> 99 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 100 | 101 | val rows = mapper.selectDistinct { 102 | where { id isGreaterThan 1 } 103 | } 104 | 105 | assertThat(rows.size).isEqualTo(4) 106 | } 107 | } 108 | 109 | @Test 110 | fun testFirstNameIn() { 111 | newSession().use { session -> 112 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 113 | 114 | val rows = mapper.select { 115 | where { firstName.isIn("Fred", "Barney") } 116 | orderBy(lastName) 117 | } 118 | 119 | assertThat(rows.size).isEqualTo(2) 120 | assertThat(rows[0].lastName).isEqualTo("Flintstone") 121 | assertThat(rows[1].lastName).isEqualTo("Rubble") 122 | } 123 | } 124 | 125 | @Test 126 | fun testDelete() { 127 | newSession().use { session -> 128 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 129 | val rows = mapper.delete { 130 | where { lastName isEqualTo "Rubble" } 131 | } 132 | assertThat(rows).isEqualTo(2) 133 | } 134 | } 135 | 136 | @Test 137 | fun testDeleteAllRows() { 138 | newSession().use { session -> 139 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 140 | val rows = mapper.delete { allRows() } 141 | assertThat(rows).isEqualTo(4) 142 | } 143 | } 144 | 145 | @Test 146 | fun testDeleteByPrimaryKey() { 147 | newSession().use { session -> 148 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 149 | val rows = mapper.deleteByPrimaryKey(22) 150 | 151 | assertThat(rows).isEqualTo(1) 152 | } 153 | } 154 | 155 | @Test 156 | fun testInsert() { 157 | newSession().use { session -> 158 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 159 | val row = GeneratedAlwaysRow(firstName = "Joe", lastName = "Jones") 160 | 161 | val rowsInserted = mapper.insert(row) 162 | assertThat(rowsInserted).isEqualTo(1) 163 | assertThat(row.id).isEqualTo(26) 164 | assertThat(row.fullName).isEqualTo("Joe Jones") 165 | } 166 | } 167 | 168 | @Test 169 | fun testInsertBatch() { 170 | newSession(ExecutorType.BATCH).use { session -> 171 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 172 | 173 | val row1 = GeneratedAlwaysRow(firstName = "Joe", lastName = "Jones") 174 | val row2 = GeneratedAlwaysRow(firstName = "Sam", lastName = "Smith") 175 | 176 | mapper.insertBatch(row1, row2) 177 | val batchResults = mapper.flush() 178 | 179 | assertThat(batchResults).hasSize(1) 180 | assertThat(batchResults.flatMap { it.updateCounts.asList() }.sum()).isEqualTo(2) 181 | assertThat(row1.id).isEqualTo(26) 182 | assertThat(row1.fullName).isEqualTo("Joe Jones") 183 | assertThat(row2.id).isEqualTo(27) 184 | assertThat(row2.fullName).isEqualTo("Sam Smith") 185 | } 186 | } 187 | 188 | @Test 189 | fun testInsertMultiple() { 190 | newSession().use { session -> 191 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 192 | 193 | val row1 = GeneratedAlwaysRow(firstName = "Joe", lastName = "Jones") 194 | val row2 = GeneratedAlwaysRow(firstName = "Sam", lastName = "Smith") 195 | 196 | val rowsInserted = mapper.insertMultiple(row1, row2) 197 | assertThat(rowsInserted).isEqualTo(2) 198 | assertThat(row1.id).isEqualTo(26) 199 | assertThat(row1.fullName).isEqualTo("Joe Jones") 200 | assertThat(row2.id).isEqualTo(27) 201 | assertThat(row2.fullName).isEqualTo("Sam Smith") 202 | } 203 | } 204 | 205 | @Test 206 | fun testInsertGeneral() { 207 | newSession().use { session -> 208 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 209 | 210 | val insertStatement = insertInto(generatedAlways) { 211 | set(firstName).toValue("Sam") 212 | set(lastName).toValue("Smith") 213 | } 214 | 215 | val rowsInserted = mapper.generalInsert(insertStatement) 216 | assertThat(rowsInserted).isEqualTo(1) 217 | assertThat(insertStatement.parameters).containsEntry("id", 26) 218 | assertThat(insertStatement.parameters).containsEntry("fullName", "Sam Smith") 219 | } 220 | } 221 | 222 | @Test 223 | fun testUpdateByPrimaryKey() { 224 | newSession().use { session -> 225 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 226 | val row = GeneratedAlwaysRow(firstName = "Joe", lastName = "Jones") 227 | 228 | var rows = mapper.insert(row) 229 | assertThat(rows).isEqualTo(1) 230 | 231 | val updateRecord = row.copy(lastName = "Smith") 232 | rows = mapper.updateByPrimaryKey(updateRecord) 233 | assertThat(rows).isEqualTo(1) 234 | 235 | val newRecord = mapper.selectByPrimaryKey(26) 236 | assertThat(newRecord?.fullName).isEqualTo("Joe Smith") 237 | } 238 | } 239 | 240 | @Test 241 | fun testUpdateByPrimaryKeySelective() { 242 | newSession().use { session -> 243 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 244 | val row = GeneratedAlwaysRow(firstName = "Joe", lastName = "Jones") 245 | 246 | var rows = mapper.insert(row) 247 | assertThat(rows).isEqualTo(1) 248 | 249 | val updateRecord = GeneratedAlwaysRow(id = 26, firstName = "Sam") 250 | rows = mapper.updateByPrimaryKeySelective(updateRecord) 251 | assertThat(rows).isEqualTo(1) 252 | 253 | val newRecord = mapper.selectByPrimaryKey(26) 254 | assertThat(newRecord?.fullName).isEqualTo("Sam Jones") 255 | } 256 | } 257 | 258 | @Test 259 | fun testUpdateByPrimaryKeySelectiveWithCopy() { 260 | newSession().use { session -> 261 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 262 | val row = GeneratedAlwaysRow(firstName = "Joe", lastName = "Jones") 263 | 264 | var rows = mapper.insert(row) 265 | assertThat(rows).isEqualTo(1) 266 | 267 | val updateRecord = row.copy(lastName = "Smith") 268 | rows = mapper.updateByPrimaryKeySelective(updateRecord) 269 | assertThat(rows).isEqualTo(1) 270 | 271 | val newRecord = mapper.selectByPrimaryKey(26) 272 | assertThat(newRecord?.fullName).isEqualTo("Joe Smith") 273 | } 274 | } 275 | 276 | @Test 277 | fun testUpdate() { 278 | newSession().use { session -> 279 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 280 | val row = GeneratedAlwaysRow(firstName = "Joe", lastName = "Jones") 281 | 282 | var rows = mapper.insert(row) 283 | assertThat(rows).isEqualTo(1) 284 | 285 | val updateRecord = row.copy(firstName = "Sam") 286 | rows = mapper.update { 287 | updateAllColumns(updateRecord) 288 | where { 289 | id isEqualTo 26 290 | and { firstName isEqualTo "Joe" } 291 | } 292 | } 293 | 294 | assertThat(rows).isEqualTo(1) 295 | 296 | val newRecord = mapper.selectByPrimaryKey(26) 297 | assertThat(newRecord?.fullName).isEqualTo("Sam Jones") 298 | } 299 | } 300 | 301 | @Test 302 | fun testUpdateAllRows() { 303 | newSession().use { session -> 304 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 305 | 306 | val updateRecord = GeneratedAlwaysRow(lastName = "Blackwell") 307 | 308 | val rows = mapper.update { 309 | updateSelectiveColumns(updateRecord) 310 | } 311 | 312 | assertThat(rows).isEqualTo(4) 313 | 314 | val newRecord = mapper.selectByPrimaryKey(22) 315 | assertThat(newRecord?.fullName).isEqualTo("Fred Blackwell") 316 | } 317 | } 318 | 319 | @Test 320 | fun testCount() { 321 | newSession().use { session -> 322 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 323 | val rows = mapper.count { 324 | where { lastName isEqualTo "Rubble" } 325 | } 326 | 327 | assertThat(rows).isEqualTo(2L) 328 | } 329 | } 330 | 331 | @Test 332 | fun testCountAll() { 333 | newSession().use { session -> 334 | val mapper = session.getMapper(GeneratedAlwaysMapper::class.java) 335 | val rows = mapper.count { allRows() } 336 | 337 | assertThat(rows).isEqualTo(4L) 338 | } 339 | } 340 | 341 | companion object { 342 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 343 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 344 | } 345 | } 346 | -------------------------------------------------------------------------------- /src/test/resources/CreateSimpleDB.sql: -------------------------------------------------------------------------------- 1 | drop table Person if exists; 2 | drop table Address if exists; 3 | drop table GeneratedAlways if exists; 4 | 5 | create table Person ( 6 | id int not null, 7 | first_name varchar(30) not null, 8 | last_name varchar(30) not null, 9 | birth_date date not null, 10 | employed varchar(3) not null, 11 | occupation varchar(30) null, 12 | address_id int not null, 13 | parent_id int null, 14 | primary key(id) 15 | ); 16 | 17 | create table Address ( 18 | id int not null, 19 | street_address varchar(30) not null, 20 | city varchar(30) not null, 21 | state char(2) not null, 22 | primary key(id) 23 | ); 24 | 25 | create table GeneratedAlways ( 26 | id int generated by default as identity(start with 22), 27 | first_name varchar(30) not null, 28 | last_name varchar(30) not null, 29 | full_name varchar(61) generated always as (first_name || ' ' || last_name), 30 | primary key(id) 31 | ); 32 | 33 | insert into Address values(1, '123 Main Street', 'Bedrock', 'IN'); 34 | insert into Address values(2, '456 Main Street', 'Bedrock', 'IN'); 35 | 36 | insert into Person values(1, 'Fred', 'Flintstone', '1935-02-01', 'Yes', 'Brontosaurus Operator', 1, null); 37 | insert into Person values(2, 'Wilma', 'Flintstone', '1940-02-01', 'Yes', 'Accountant', 1, null); 38 | insert into Person(id, first_name, last_name, birth_date, employed, address_id, parent_id) values(3, 'Pebbles', 'Flintstone', '1960-05-06', 'No', 1, 2); 39 | insert into Person values(4, 'Barney', 'Rubble', '1937-02-01', 'Yes', 'Brontosaurus Operator', 2, null); 40 | insert into Person values(5, 'Betty', 'Rubble', '1943-02-01', 'Yes', 'Engineer', 2, null); 41 | insert into Person(id, first_name, last_name, birth_date, employed, address_id, parent_id) values(6, 'Bamm Bamm', 'Rubble', '1963-07-08', 'No', 2, 4); 42 | 43 | insert into GeneratedAlways(first_name, last_name) values('Fred', 'Flintstone'); 44 | insert into GeneratedAlways(first_name, last_name) values('Wilma', 'Flintstone'); 45 | insert into GeneratedAlways(first_name, last_name) values('Barney', 'Rubble'); 46 | insert into GeneratedAlways(first_name, last_name) values('Betty', 'Rubble'); 47 | --------------------------------------------------------------------------------