├── gradle.properties ├── settings.gradle.kts ├── .gitignore ├── .gitattributes ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── src ├── main │ └── kotlin │ │ ├── example08 │ │ ├── Example08Mapper.kt │ │ ├── Example08Model.kt │ │ └── Example08Mapper.xml │ │ ├── example06 │ │ ├── GeneratedAlwaysRow.kt │ │ ├── GeneratedAlwaysDynamicSqlSupport.kt │ │ └── GeneratedAlwaysMapper.kt │ │ ├── example01 │ │ ├── Example01Mapper.kt │ │ └── Example01Model.kt │ │ ├── example02 │ │ ├── Example02Mapper.kt │ │ ├── oldmybatis │ │ │ ├── Example02OldMyBatisMapper.kt │ │ │ └── Example02OldMyBatisModel.kt │ │ └── Example02Model.kt │ │ ├── example05 │ │ ├── Example05Model.kt │ │ ├── PersonDynamicSqlSupport.kt │ │ └── PersonMapper.kt │ │ ├── example04 │ │ ├── Example04Mapper.kt │ │ ├── Example04Mapper.xml │ │ ├── Example04Model.kt │ │ └── lazy │ │ │ ├── Example04LazyModel.kt │ │ │ └── Example04LazyMapper.kt │ │ ├── example07 │ │ ├── Example07Model.kt │ │ ├── Example07Mapper.kt │ │ └── Example07Mapper.xml │ │ ├── util │ │ ├── YesNoTypeHandler.kt │ │ └── MatchesAny.kt │ │ └── example03 │ │ ├── Example03Mapper.kt │ │ └── Example03Model.kt └── test │ ├── resources │ └── CreateSimpleDB.sql │ └── kotlin │ ├── example04 │ ├── Example04Test.kt │ └── lazy │ │ └── Example04LazyTest.kt │ ├── example01 │ └── Example01Test.kt │ ├── example02 │ ├── Example02Test.kt │ └── oldmybatis │ │ └── Example02OldMyBatisTest.kt │ ├── example05 │ ├── StatementConfigurationTest.kt │ └── Example05Test.kt │ ├── example03 │ └── Example03Test.kt │ ├── example07 │ └── Example07Test.kt │ ├── example08 │ └── Example08Test.kt │ └── example06 │ └── Example06Test.kt ├── LICENSE.txt ├── gradlew.bat ├── README.md └── gradlew /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "mybatis-kotlin-examples" 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | .idea 3 | .gradle 4 | build 5 | local.properties 6 | *.iml 7 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set default behaviour, in case users don't have core.autocrlf set. 2 | * text=auto 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeffgbutler/mybatis-kotlin-examples/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/main/kotlin/example08/Example08Mapper.kt: -------------------------------------------------------------------------------- 1 | package example08 2 | 3 | interface Example08Mapper { 4 | fun selectAddressById(id: Int): AddressWithPeople 5 | 6 | fun selectPersonById(id: Int): PersonWithAddress 7 | } 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /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/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/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/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/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/example07/Example07Model.kt: -------------------------------------------------------------------------------- 1 | package example07 2 | 3 | import java.time.LocalDate 4 | 5 | /* 6 | * In this example we will use explicit constructor mapping - both annotation and XML based. 7 | * 8 | * 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 9 | * need to write a type handler to convert the database string to a Boolean. That type handler is 10 | * util.YesNoTypeHandler. 11 | */ 12 | data class Person( 13 | val id: Int, 14 | val firstName: String, 15 | val lastName: String, 16 | val birthDate: LocalDate, 17 | val employed: Boolean, 18 | val occupation: String? 19 | ) 20 | -------------------------------------------------------------------------------- /.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: [17, 21, 25] 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 | -------------------------------------------------------------------------------- /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/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/example07/Example07Mapper.kt: -------------------------------------------------------------------------------- 1 | package example07 2 | 3 | import org.apache.ibatis.annotations.Arg 4 | import org.apache.ibatis.annotations.Select 5 | import util.YesNoTypeHandler 6 | import java.time.LocalDate 7 | 8 | interface Example07Mapper { 9 | 10 | @Select( 11 | "select id, first_name, last_name, birth_date, employed, occupation", 12 | "from Person where id = #{value}" 13 | ) 14 | @Arg(column = "id", javaType = Int::class, id = true) 15 | @Arg(column = "first_name", javaType = String::class) 16 | @Arg(column = "last_name", javaType = String::class) 17 | @Arg(column = "birth_date", javaType = LocalDate::class) 18 | @Arg(column = "employed", javaType = Boolean::class, typeHandler = YesNoTypeHandler::class) 19 | @Arg(column = "occupation", javaType = String::class) 20 | fun selectPersonByIdWithAnnotations(id: Int): Person 21 | 22 | fun selectPersonByIdWithXMLMapping(id: Int): Person 23 | } 24 | -------------------------------------------------------------------------------- /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/example04/Example04Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/example07/Example07Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 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/example08/Example08Model.kt: -------------------------------------------------------------------------------- 1 | package example08 2 | 3 | import java.time.LocalDate 4 | 5 | /* 6 | * In this version of the model, all classes are fully immutable. With MyBatis 3.6 and later, we can make these classes 7 | * immutable because starting with that version, MyBatis is able to build nested properties before calling the outer 8 | * constructor. 9 | * 10 | * We still need to use XML for defining the result maps - this is because the MyBatis annotations cannot be used to 11 | * describe nested collections. 12 | */ 13 | 14 | data class AddressWithPeople( 15 | val id: Int, 16 | val streetAddress: String, 17 | val city: String, 18 | val state: String, 19 | val people: List 20 | ) 21 | 22 | data class Person( 23 | val id: Int, 24 | val firstName: String, 25 | val lastName: String, 26 | val birthDate: LocalDate, 27 | val employed: Boolean, 28 | val occupation: String? 29 | ) 30 | 31 | data class Address( 32 | val id: Int, 33 | val streetAddress: String, 34 | val city: String, 35 | val state: String 36 | ) 37 | 38 | data class PersonWithAddress( 39 | val id: Int, 40 | val firstName: String, 41 | val lastName: String, 42 | val birthDate: LocalDate, 43 | val employed: Boolean, 44 | val occupation: String?, 45 | val address: Address? 46 | ) 47 | -------------------------------------------------------------------------------- /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/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/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/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 in various ways 15 | 16 | // The following shows how to extend the DSL without using any experimental features. 17 | // It is somewhat less elegant than the context parameters method shown below, but it doesn't require the use of an 18 | // experimental compiler feature 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 extend the DSL with the experimental Context Parameters method 29 | // https://github.com/Kotlin/KEEP/blob/context-parameters/proposals/context-parameters.md 30 | // This requires use of the compiler flag -Xcontext-parameters 31 | context (collector: GroupingCriteriaCollector) 32 | infix fun BindableColumn.matchesAny(subQueryBuilder: KotlinSubQueryBuilder.() -> Unit) = 33 | with(collector) { 34 | invoke(MatchesAny(KotlinSubQueryBuilder().apply(subQueryBuilder))) 35 | } 36 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /src/main/kotlin/example08/Example08Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 40 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /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/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/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 java.io.InputStreamReader 19 | import java.sql.DriverManager 20 | 21 | class StatementConfigurationTest { 22 | private fun newSession(executorType: ExecutorType = ExecutorType.REUSE): SqlSession { 23 | Class.forName(Example05Test.JDBC_DRIVER) 24 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 25 | DriverManager.getConnection(Example05Test.JDBC_URL, "sa", "").use { connection -> 26 | val sr = ScriptRunner(connection) 27 | sr.setLogWriter(null) 28 | sr.runScript(InputStreamReader(script!!)) 29 | } 30 | 31 | val ds = UnpooledDataSource(Example05Test.JDBC_DRIVER, Example05Test.JDBC_URL, "sa", "") 32 | val environment = Environment("test", JdbcTransactionFactory(), ds) 33 | val config = Configuration(environment) 34 | config.addMapper(PersonMapper::class.java) 35 | config.addMapper(CommonSelectMapper::class.java) 36 | return SqlSessionFactoryBuilder().build(config).openSession(executorType) 37 | } 38 | 39 | @Test 40 | fun testSelectAllRows() { 41 | val rows = search(null, null, true) 42 | assertThat(rows.size).isEqualTo(6) 43 | } 44 | 45 | @Test 46 | fun testSelectSomeRowsByFirstName() { 47 | val rows = search("fr", null, false) 48 | assertThat(rows.size).isEqualTo(1) 49 | } 50 | 51 | @Test 52 | fun testSelectSomeRowsByLastName() { 53 | val rows = search(null,"fl", false) 54 | assertThat(rows).hasSize(3) 55 | assertThat(rows.all { (it.lastName!!).startsWith("Ru") }) 56 | } 57 | 58 | @Test 59 | fun testSearchCriteriaRequired() { 60 | assertThatExceptionOfType(NonRenderingWhereClauseException::class.java).isThrownBy { 61 | search(null, null, false) 62 | } 63 | } 64 | 65 | private fun search(firstName: String?, lastName: String?, allowSearchAll: Boolean): List { 66 | fun String.addWildcards() = "%$this%" 67 | 68 | newSession().use { session -> 69 | val mapper = session.getMapper(PersonMapper::class.java) 70 | 71 | return mapper.select { 72 | where { 73 | person.firstName (isLikeCaseInsensitiveWhenPresent(firstName) 74 | .filter{ it.isNotEmpty() } 75 | .map { it.addWildcards() }) 76 | and { 77 | person.lastName (isLikeCaseInsensitiveWhenPresent(lastName) 78 | .filter{ it.isNotEmpty() } 79 | .map { it.addWildcards()}) 80 | } 81 | } 82 | configureStatement { isNonRenderingWhereClauseAllowed = allowSearchAll } 83 | } 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /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/example07/Example07Test.kt: -------------------------------------------------------------------------------- 1 | package example07 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 Example07Test { 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(Example07Mapper::class.java) 30 | return SqlSessionFactoryBuilder().build(config).openSession() 31 | } 32 | 33 | @Test 34 | fun selectPersonWithAllFields() { 35 | newSession().use { session -> 36 | val mapper = session.getMapper(Example07Mapper::class.java) 37 | 38 | val person = mapper.selectPersonByIdWithAnnotations(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 | } 47 | } 48 | 49 | @Test 50 | fun selectPersonWithNullOccupation() { 51 | newSession().use { session -> 52 | val mapper = session.getMapper(Example07Mapper::class.java) 53 | 54 | val person = mapper.selectPersonByIdWithAnnotations(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).isFalse 61 | assertThat(person.occupation).isNull() 62 | } 63 | } 64 | 65 | @Test 66 | fun selectPersonWithNullOccupationAndElvisOperator() { 67 | newSession().use { session -> 68 | val mapper = session.getMapper(Example07Mapper::class.java) 69 | 70 | val person = mapper.selectPersonByIdWithAnnotations(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).isFalse 77 | assertThat(person.occupation ?: "").isEqualTo("") 78 | } 79 | } 80 | 81 | @Test 82 | fun selectPersonWithNullOccupationAndXMLMapping() { 83 | newSession().use { session -> 84 | val mapper = session.getMapper(Example07Mapper::class.java) 85 | 86 | val person = mapper.selectPersonByIdWithXMLMapping(3) 87 | 88 | assertThat(person.id).isEqualTo(3) 89 | assertThat(person.firstName).isEqualTo("Pebbles") 90 | assertThat(person.lastName).isEqualTo("Flintstone") 91 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 92 | assertThat(person.employed).isFalse 93 | assertThat(person.occupation).isNull() 94 | } 95 | } 96 | 97 | @Test 98 | fun selectPersonWithAllFieldsAndXMLMapping() { 99 | newSession().use { session -> 100 | val mapper = session.getMapper(Example07Mapper::class.java) 101 | 102 | val person = mapper.selectPersonByIdWithXMLMapping(1) 103 | 104 | assertThat(person.id).isEqualTo(1) 105 | assertThat(person.firstName).isEqualTo("Fred") 106 | assertThat(person.lastName).isEqualTo("Flintstone") 107 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1935, 2, 1)) 108 | assertThat(person.employed).isTrue 109 | assertThat(person.occupation).isEqualTo("Brontosaurus Operator") 110 | } 111 | } 112 | 113 | companion object { 114 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 115 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/test/kotlin/example08/Example08Test.kt: -------------------------------------------------------------------------------- 1 | package example08 2 | 3 | import java.io.InputStreamReader 4 | import java.sql.DriverManager 5 | import java.time.LocalDate 6 | 7 | import org.assertj.core.api.Assertions.assertThat 8 | import org.apache.ibatis.datasource.unpooled.UnpooledDataSource 9 | import org.apache.ibatis.jdbc.ScriptRunner 10 | import org.apache.ibatis.mapping.Environment 11 | import org.apache.ibatis.session.Configuration 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.junit.jupiter.api.Test 16 | 17 | class Example08Test { 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 | config.addMapper(Example08Mapper::class.java) 31 | return SqlSessionFactoryBuilder().build(config).openSession() 32 | } 33 | 34 | @Test 35 | fun selectAddressById() { 36 | newSession().use { session -> 37 | val mapper = session.getMapper(Example08Mapper::class.java) 38 | 39 | val address = mapper.selectAddressById(1) 40 | 41 | assertThat(address.id).isEqualTo(1) 42 | assertThat(address.streetAddress).isEqualTo("123 Main Street") 43 | assertThat(address.city).isEqualTo("Bedrock") 44 | assertThat(address.state).isEqualTo("IN") 45 | 46 | assertThat(address.people.size).isEqualTo(3) 47 | 48 | assertThat(address.people[0].firstName).isEqualTo("Fred") 49 | assertThat(address.people[0].lastName).isEqualTo("Flintstone") 50 | assertThat(address.people[0].birthDate).isEqualTo(LocalDate.of(1935, 2, 1)) 51 | assertThat(address.people[0].employed).isTrue 52 | assertThat(address.people[0].occupation).isEqualTo("Brontosaurus Operator") 53 | 54 | assertThat(address.people[1].firstName).isEqualTo("Wilma") 55 | assertThat(address.people[1].lastName).isEqualTo("Flintstone") 56 | assertThat(address.people[1].birthDate).isEqualTo(LocalDate.of(1940, 2, 1)) 57 | assertThat(address.people[1].employed).isTrue 58 | assertThat(address.people[1].occupation).isEqualTo("Accountant") 59 | 60 | assertThat(address.people[2].firstName).isEqualTo("Pebbles") 61 | assertThat(address.people[2].lastName).isEqualTo("Flintstone") 62 | assertThat(address.people[2].birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 63 | assertThat(address.people[2].employed).isFalse 64 | assertThat(address.people[2].occupation).isNull() 65 | } 66 | } 67 | 68 | @Test 69 | fun selectPersonWithAllFields() { 70 | newSession().use { session -> 71 | val mapper = session.getMapper(Example08Mapper::class.java) 72 | 73 | val person = mapper.selectPersonById(1) 74 | 75 | assertThat(person.id).isEqualTo(1) 76 | assertThat(person.firstName).isEqualTo("Fred") 77 | assertThat(person.lastName).isEqualTo("Flintstone") 78 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1935, 2, 1)) 79 | assertThat(person.employed).isTrue 80 | assertThat(person.occupation).isEqualTo("Brontosaurus Operator") 81 | assertThat(person.address?.id).isEqualTo(1) 82 | assertThat(person.address?.streetAddress).isEqualTo("123 Main Street") 83 | assertThat(person.address?.city).isEqualTo("Bedrock") 84 | assertThat(person.address?.state).isEqualTo("IN") 85 | } 86 | } 87 | 88 | @Test 89 | fun selectPersonWithNullOccupation() { 90 | newSession().use { session -> 91 | val mapper = session.getMapper(Example08Mapper::class.java) 92 | 93 | val person = mapper.selectPersonById(3) 94 | 95 | assertThat(person.id).isEqualTo(3) 96 | assertThat(person.firstName).isEqualTo("Pebbles") 97 | assertThat(person.lastName).isEqualTo("Flintstone") 98 | assertThat(person.birthDate).isEqualTo(LocalDate.of(1960, 5, 6)) 99 | assertThat(person.employed).isFalse 100 | assertThat(person.occupation).isNull() 101 | assertThat(person.address?.id).isEqualTo(1) 102 | assertThat(person.address?.streetAddress).isEqualTo("123 Main Street") 103 | assertThat(person.address?.city).isEqualTo("Bedrock") 104 | assertThat(person.address?.state).isEqualTo("IN") 105 | } 106 | } 107 | 108 | companion object { 109 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 110 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MyBatis Kotlin Examples 2 | 3 | This project demonstrates the 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 the 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 | Note that with MyBatis 3.6 and later, we can make the classes fully immutable. Starting with that version, MyBatis is 23 | able to build a nested collection before calling the outer constructor. Example08 shows how to configure this. 24 | 25 | ### example01 — Auto Mapping 26 | 27 | This example shows that MyBatis is able to create simple objects (basic data types, no nested classes) with idiomatic 28 | Kotlin. The "model" classes are Kotlin data classes with a mix of nullable and non-nullable types. No special mapping 29 | is needed in MyBatis. MyBatis can auto discover class constructors in this case. The important distinction is there are 30 | no nested classes or group-by functions 31 | 32 | ### example02 — Type Handlers and Advanced Auto Mapping 33 | 34 | This example shows the use of TypeHandlers. With this example we have moved beyond simple types. 35 | We are still using immutable types, but in this case we have a non-standard type that requires a 36 | TypeHandler. Important code changes: 37 | 38 | 1. Look in `/src/main/kotlin/util/YesNoTypeHandler.kt` to see how to write the type handler 39 | 2. Look in `/src/test/kotlin/example02/Example02Test.kt` to see how to register the type handler 40 | 41 | ### example02.oldmybatis - Type Handlers and Advanced Auto Mapping in Older MyBatis Versions 42 | 43 | This example shows the use of classes that need TypeHandlers in older versions of MyBatis. In MyBatis versions prior to 44 | 3.5.0, MyBatis sometimes had difficulty finding constructors on classes that included types with TypeHandlers. 45 | In that case, we need to annotate the class constructor 46 | with the `@AutomapConstructor` annotation and also register the type handler. Important code changes: 47 | 48 | 1. Look in `/src/main/kotlin/example02/oldmybatis/Example02Model.kt` to see how to annotate the class 49 | 2. Look in `/src/main/kotlin/util/YesNoTypeHandler.kt` to see how to write the type handler 50 | 3. Look in `/src/test/kotlin/example02/oldmybatis/Example02Test.kt` to see how to register the type handler 51 | 52 | ### example03 — Nested Objects 53 | 54 | This example shows how to write Kotlin for a class hierarchy where a class (Person in this case) has an 55 | attribute that is another class (Address in this case). With this example we can no longer use Kotlin 56 | immutable data classes because of the way that MyBatis constructs an object graph in cases like this. 57 | 58 | Note that this example uses mutable objects, which are not exactly idiomatic Kotlin. This shows how to use MyBatis for 59 | nested collections with MyBatis version prior to 3.6.0. After that version, MyBatis is able to build nested object 60 | graphs that are fully immutable. See Example08 for how to use fully immutable result objects. 61 | 62 | ### example04 — Join Queries with Nested Collections 63 | 64 | This example shows how to use MyBatis support for N+1 query mitigation. This involves creating a 65 | result map with a nested collection. Currently, this is only supported in MyBatis using XML to define the 66 | result map. 67 | 68 | Note that this example uses mutable objects, which are not exactly idiomatic Kotlin. This shows how to use MyBatis for 69 | nested collections with MyBatis version prior to 3.6.0. After that version, MyBatis is able to build nested object 70 | graphs that are fully immutable. See Example08 for how to use fully immutable result objects. 71 | 72 | ### example04.lazy - Lazy Loaded Nested Collections 73 | 74 | This example shows how to use MyBatis support for lazy loaded associations. This forces an N+1 query (or worse), 75 | so be careful with lazy loading. There are also issues with lazy loading and Kotlin due to the way that Javassist 76 | works (MyBatis uses Javassist to create dynamic proxies when you use lazy loading). Any class that will be 77 | lazily loaded, and any field in that class that will be lazily loaded, must be declared "open" in Kotlin. 78 | We can code queries like this without XML, which is good, but the performance may be worse — tradeoffs. 79 | 80 | ### example05 — MyBatis Dynamic SQL 81 | 82 | This example shows how to use Kotlin to interact with the "MyBatis Dynamic SQL" library, 83 | and it shows how MyBatis Generator creates code for Kotlin. 84 | 85 | The example also shows how to extend the DSL to support a new SQL function. This can be done in two ways: 86 | 87 | 1. Using Kotlin's experimental Context Parameters feature — which makes for an elegant DSL extension that looks the same 88 | as the built-in functions 89 | 2. Using no experimental features and sacrificing some elegance 90 | 91 | ### example06 — MyBatis Dynamic SQL (Generated Values) 92 | 93 | This example shows how to use Kotlin to interact with the "MyBatis Dynamic SQL" library when a 94 | table contains generated values. 95 | This example also shows how MyBatis Generator creates code for Kotlin. 96 | 97 | ### example07 — Explicit Constructor Mappings 98 | Example02 showed how MyBatis can automap constructors. Example07 shows how to explicitly map constructors, using both 99 | annotations and XML. The key learning is that Kotlin's handling of primitive types can be confusing. A non-nullable 100 | primitive type maps to a true Java primitive type, but a nullable primitive will map to the Java wrapper type. 101 | In XML configuration, you must use the proper type aliases for these types. The following table shows examples of these 102 | mappings: 103 | 104 | | Kotlin Type | Java Type | MyBatis Alias | 105 | |-------------|-----------|---------------| 106 | | Int | int | _int | 107 | | Int? | Integer | int | 108 | | Boolean | boolean | _boolean | 109 | | Boolean? | Boolean | boolean | 110 | 111 | ### example08 — Fully Immutable Object Graphs 112 | Starting with MyBatis version 3.6, MyBatis can build object graphs with nested objects and collections that are fully 113 | immutable. This example shows how to do this. We still need to define the result maps in XML, but the code is much 114 | more compatible with idiomatic Kotlin. 115 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /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/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.matchesAny 23 | import java.io.InputStreamReader 24 | import java.sql.DriverManager 25 | import java.time.LocalDate 26 | 27 | internal class Example05Test { 28 | 29 | private fun newSession(executorType: ExecutorType = ExecutorType.REUSE): SqlSession { 30 | Class.forName(JDBC_DRIVER) 31 | val script = javaClass.getResourceAsStream("/CreateSimpleDB.sql") 32 | DriverManager.getConnection(JDBC_URL, "sa", "").use { connection -> 33 | val sr = ScriptRunner(connection) 34 | sr.setLogWriter(null) 35 | sr.runScript(InputStreamReader(script!!)) 36 | } 37 | 38 | val ds = UnpooledDataSource(JDBC_DRIVER, JDBC_URL, "sa", "") 39 | val environment = Environment("test", JdbcTransactionFactory(), ds) 40 | val config = Configuration(environment) 41 | config.addMapper(PersonMapper::class.java) 42 | config.addMapper(CommonSelectMapper::class.java) 43 | return SqlSessionFactoryBuilder().build(config).openSession(executorType) 44 | } 45 | 46 | @Test 47 | fun testSelect() { 48 | newSession().use { session -> 49 | val mapper = session.getMapper(PersonMapper::class.java) 50 | 51 | val rows = mapper.select { 52 | where { 53 | id isEqualTo 1 54 | or { occupation.isNull() } 55 | } 56 | orderBy(id) 57 | } 58 | 59 | assertThat(rows.size).isEqualTo(3) 60 | assertThat(rows[0].id).isEqualTo(1) 61 | assertThat(rows[0].firstName).isEqualTo("Fred") 62 | assertThat(rows[0].lastName).isEqualTo("Flintstone") 63 | assertThat(rows[0].birthDate).isNotNull 64 | assertThat(rows[0].employed).isTrue 65 | assertThat(rows[0].occupation).isEqualTo("Brontosaurus Operator") 66 | assertThat(rows[0].addressId).isEqualTo(1) 67 | assertThat(rows[0].parentId).isNull() 68 | } 69 | } 70 | 71 | @Test 72 | fun testSelectAllRows() { 73 | newSession().use { session -> 74 | val mapper = session.getMapper(PersonMapper::class.java) 75 | 76 | val rows = mapper.select { allRows() } 77 | 78 | assertThat(rows.size).isEqualTo(6) 79 | } 80 | } 81 | 82 | @Test 83 | fun testSelectAllRowsWithOrder() { 84 | newSession().use { session -> 85 | val mapper = session.getMapper(PersonMapper::class.java) 86 | 87 | val rows = mapper.select { 88 | allRows() 89 | orderBy(firstName, lastName) 90 | } 91 | 92 | assertThat(rows.size).isEqualTo(6) 93 | assertThat(rows[0].firstName).isEqualTo("Bamm Bamm") 94 | } 95 | } 96 | 97 | @Test 98 | fun testSelectByPrimaryKeyNoRecord() { 99 | newSession().use { session -> 100 | val mapper = session.getMapper(PersonMapper::class.java) 101 | 102 | val row = mapper.selectByPrimaryKey(22) 103 | 104 | assertThat(row?.id).isNull() 105 | assertThat(row).isNull() 106 | } 107 | } 108 | 109 | @Test 110 | fun testSelectDistinct() { 111 | newSession().use { session -> 112 | val mapper = session.getMapper(PersonMapper::class.java) 113 | 114 | val rows = mapper.selectDistinct { 115 | where { 116 | id isGreaterThan 1 117 | or { occupation.isNull() } 118 | } 119 | } 120 | 121 | assertThat(rows.size).isEqualTo(5) 122 | } 123 | } 124 | 125 | @Test 126 | fun testSelectWithTypeHandler() { 127 | newSession().use { session -> 128 | val mapper = session.getMapper(PersonMapper::class.java) 129 | 130 | val rows = mapper.select { 131 | where { employed isEqualTo false } 132 | orderBy(id) 133 | } 134 | 135 | assertThat(rows.size).isEqualTo(2) 136 | assertThat(rows[0].id).isEqualTo(3) 137 | assertThat(rows[1].id).isEqualTo(6) 138 | } 139 | } 140 | 141 | @Test 142 | fun testFirstNameIn() { 143 | newSession().use { session -> 144 | val mapper = session.getMapper(PersonMapper::class.java) 145 | 146 | val rows = mapper.select { where { firstName.isIn("Fred", "Barney") } } 147 | 148 | assertThat(rows.size).isEqualTo(2) 149 | assertThat(rows[0].lastName).isEqualTo("Flintstone") 150 | assertThat(rows[1].lastName).isEqualTo("Rubble") 151 | } 152 | } 153 | 154 | @Test 155 | fun testDelete() { 156 | newSession().use { session -> 157 | val mapper = session.getMapper(PersonMapper::class.java) 158 | val rows = mapper.delete { where { occupation.isNull() } } 159 | assertThat(rows).isEqualTo(2) 160 | } 161 | } 162 | 163 | @Test 164 | fun testDeleteAllRows() { 165 | newSession().use { session -> 166 | val mapper = session.getMapper(PersonMapper::class.java) 167 | val rows = mapper.delete { allRows() } 168 | assertThat(rows).isEqualTo(6) 169 | } 170 | } 171 | 172 | @Test 173 | fun testDeleteByPrimaryKey() { 174 | newSession().use { session -> 175 | val mapper = session.getMapper(PersonMapper::class.java) 176 | val rows = mapper.deleteByPrimaryKey(2) 177 | 178 | assertThat(rows).isEqualTo(1) 179 | } 180 | } 181 | 182 | @Test 183 | fun testInsert() { 184 | newSession().use { session -> 185 | val mapper = session.getMapper(PersonMapper::class.java) 186 | val record = PersonRecord(10, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 187 | 188 | val rows = mapper.insert(record) 189 | assertThat(rows).isEqualTo(1) 190 | } 191 | } 192 | 193 | @Test 194 | fun testInsertMultiple() { 195 | newSession().use { session -> 196 | val mapper = session.getMapper(PersonMapper::class.java) 197 | 198 | val rows = mapper.insertMultiple( 199 | PersonRecord(10, "Joe", "Jones", LocalDate.now(), true, "Developer", 22), 200 | PersonRecord(11, "Sam", "Smith", LocalDate.now(), true, "Architect", 23) 201 | ) 202 | assertThat(rows).isEqualTo(2) 203 | } 204 | } 205 | 206 | @Test 207 | fun testInsertBatch() { 208 | newSession(ExecutorType.BATCH).use { session -> 209 | val mapper = session.getMapper(PersonMapper::class.java) 210 | 211 | mapper.insertBatch( 212 | PersonRecord(10, "Joe", "Jones", LocalDate.now(), true, "Developer", 22), 213 | PersonRecord(11, "Sam", "Smith", LocalDate.now(), true, "Architect", 23) 214 | ) 215 | 216 | val batchResults = mapper.flush() 217 | assertThat(batchResults).hasSize(1) 218 | assertThat(batchResults.flatMap { it.updateCounts.asList() }.sum()).isEqualTo(2) 219 | } 220 | } 221 | 222 | @Test 223 | fun testInsertWithNull() { 224 | newSession().use { session -> 225 | val mapper = session.getMapper(PersonMapper::class.java) 226 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), false, null, 22) 227 | 228 | val rows = mapper.insert(record) 229 | assertThat(rows).isEqualTo(1) 230 | } 231 | } 232 | 233 | @Test 234 | fun testUpdateByPrimaryKey() { 235 | newSession().use { session -> 236 | val mapper = session.getMapper(PersonMapper::class.java) 237 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 238 | 239 | var rows = mapper.insert(record) 240 | assertThat(rows).isEqualTo(1) 241 | 242 | val updateRecord = record.copy(occupation = "Programmer") 243 | rows = mapper.updateByPrimaryKey(updateRecord) 244 | assertThat(rows).isEqualTo(1) 245 | 246 | val newRecord = mapper.selectByPrimaryKey(100) 247 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 248 | } 249 | } 250 | 251 | @Test 252 | fun testUpdateByPrimaryKeySelective() { 253 | newSession().use { session -> 254 | val mapper = session.getMapper(PersonMapper::class.java) 255 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 256 | 257 | var rows = mapper.insert(record) 258 | assertThat(rows).isEqualTo(1) 259 | 260 | val updateRecord = PersonRecord(id = 100, occupation = "Programmer") 261 | rows = mapper.updateByPrimaryKeySelective(updateRecord) 262 | assertThat(rows).isEqualTo(1) 263 | 264 | val newRecord = mapper.selectByPrimaryKey(100) 265 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 266 | assertThat(newRecord?.firstName).isEqualTo("Joe") 267 | 268 | } 269 | } 270 | 271 | @Test 272 | fun testUpdateByPrimaryKeySelectiveWithCopy() { 273 | newSession().use { session -> 274 | val mapper = session.getMapper(PersonMapper::class.java) 275 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 276 | 277 | var rows = mapper.insert(record) 278 | assertThat(rows).isEqualTo(1) 279 | 280 | val updateRecord = record.copy(occupation = "Programmer") 281 | rows = mapper.updateByPrimaryKeySelective(updateRecord) 282 | assertThat(rows).isEqualTo(1) 283 | 284 | val newRecord = mapper.selectByPrimaryKey(100) 285 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 286 | assertThat(newRecord?.firstName).isEqualTo("Joe") 287 | } 288 | } 289 | 290 | @Test 291 | fun testUpdateWithNulls() { 292 | newSession().use { session -> 293 | val mapper = session.getMapper(PersonMapper::class.java) 294 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 295 | 296 | var rows = mapper.insert(record) 297 | assertThat(rows).isEqualTo(1) 298 | 299 | rows = mapper.update { 300 | set(occupation).equalToNull() 301 | set(employed).equalTo(false) 302 | where { id isEqualTo 100 } 303 | } 304 | 305 | assertThat(rows).isEqualTo(1) 306 | 307 | val newRecord = mapper.selectByPrimaryKey(100) 308 | assertThat(newRecord?.occupation).isNull() 309 | assertThat(newRecord?.employed).isEqualTo(false) 310 | assertThat(newRecord?.firstName).isEqualTo("Joe") 311 | } 312 | } 313 | 314 | @Test 315 | fun testUpdate() { 316 | newSession().use { session -> 317 | val mapper = session.getMapper(PersonMapper::class.java) 318 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 319 | 320 | var rows = mapper.insert(record) 321 | assertThat(rows).isEqualTo(1) 322 | 323 | val updateRecord = record.copy(occupation = "Programmer") 324 | rows = mapper.update { 325 | updateAllColumns(updateRecord) 326 | where { 327 | id isEqualTo 100 328 | and { firstName isEqualTo "Joe" } 329 | } 330 | } 331 | 332 | assertThat(rows).isEqualTo(1) 333 | 334 | val newRecord = mapper.selectByPrimaryKey(100) 335 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 336 | } 337 | } 338 | 339 | @Test 340 | fun testUpdateAllRows() { 341 | newSession().use { session -> 342 | val mapper = session.getMapper(PersonMapper::class.java) 343 | val record = PersonRecord(100, "Joe", "Jones", LocalDate.now(), true, "Developer", 22) 344 | 345 | var rows = mapper.insert(record) 346 | assertThat(rows).isEqualTo(1) 347 | 348 | val updateRecord = PersonRecord(occupation = "Programmer") 349 | 350 | rows = mapper.update { 351 | updateSelectiveColumns(updateRecord) 352 | } 353 | 354 | assertThat(rows).isEqualTo(7) 355 | 356 | val newRecord = mapper.selectByPrimaryKey(100) 357 | assertThat(newRecord?.occupation).isEqualTo("Programmer") 358 | } 359 | } 360 | 361 | @Test 362 | fun testCount() { 363 | newSession().use { session -> 364 | val mapper = session.getMapper(PersonMapper::class.java) 365 | val rows = mapper.count { where { occupation.isNull() } } 366 | 367 | assertThat(rows).isEqualTo(2L) 368 | } 369 | } 370 | 371 | @Test 372 | fun testCountAll() { 373 | newSession().use { session -> 374 | val mapper = session.getMapper(PersonMapper::class.java) 375 | val rows = mapper.count { allRows() } 376 | 377 | assertThat(rows).isEqualTo(6L) 378 | } 379 | } 380 | 381 | @Test 382 | fun testSelfJoin() { 383 | newSession().use { session -> 384 | val mapper = session.getMapper(CommonSelectMapper::class.java) 385 | 386 | val person2 = PersonDynamicSqlSupport.Person() 387 | 388 | // get Bamm Bamm's parent - should be Barney 389 | val selectStatement = select(id, firstName, parentId) { 390 | from(person, "p1") 391 | join(person2, "p2") on { id isEqualTo person2.parentId} 392 | where { person2.id isEqualTo 6 } 393 | } 394 | 395 | val expectedStatement = ("select p1.id, p1.first_name, p1.parent_id" 396 | + " from Person p1 join Person p2 on p1.id = p2.parent_id" 397 | + " where p2.id = #{parameters.p1,jdbcType=INTEGER}") 398 | assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) 399 | 400 | val row = mapper.selectOneMappedRow(selectStatement) 401 | 402 | assertThat(row).isNotNull 403 | assertThat(row).containsEntry("ID", 4) 404 | assertThat(row).containsEntry("FIRST_NAME", "Barney") 405 | assertThat(row).doesNotContainKey("PARENT_ID") 406 | } 407 | } 408 | 409 | @Test 410 | fun testReceiverFunctionWithExplicitContext() { 411 | newSession().use { session -> 412 | val mapper = session.getMapper(CommonSelectMapper::class.java) 413 | 414 | // find all children with a convoluted query 415 | val selectStatement = select(id, firstName, lastName) { 416 | from(person) 417 | where { 418 | id.matchesAny(this) { 419 | select (id) { 420 | from(person) 421 | where { 422 | parentId.isNotNull() 423 | } 424 | } 425 | } 426 | } 427 | orderBy(id) 428 | } 429 | 430 | val expected = "select id, first_name, last_name from Person " + 431 | "where id = any (select id from Person where parent_id is not null) order by id" 432 | 433 | assertThat(selectStatement.selectStatement).isEqualTo(expected) 434 | 435 | val rows = mapper.selectManyMappedRows(selectStatement) 436 | 437 | assertThat(rows).hasSize(2) 438 | assertThat(rows[0]["FIRST_NAME"]).isEqualTo("Pebbles") 439 | assertThat(rows[1]["FIRST_NAME"]).isEqualTo("Bamm Bamm") 440 | } 441 | } 442 | 443 | @Test 444 | fun testReceiverFunctionWithContextParameter() { 445 | newSession().use { session -> 446 | val mapper = session.getMapper(CommonSelectMapper::class.java) 447 | 448 | // find all children with a convoluted query 449 | val selectStatement = select(id, firstName, lastName) { 450 | from(person) 451 | where { 452 | id matchesAny { 453 | select (id) { 454 | from(person) 455 | where { 456 | parentId.isNotNull() 457 | } 458 | } 459 | } 460 | } 461 | orderBy(id) 462 | } 463 | 464 | val expected = "select id, first_name, last_name from Person " + 465 | "where id = any (select id from Person where parent_id is not null) order by id" 466 | 467 | assertThat(selectStatement.selectStatement).isEqualTo(expected) 468 | 469 | val rows = mapper.selectManyMappedRows(selectStatement) 470 | 471 | assertThat(rows).hasSize(2) 472 | assertThat(rows[0]["FIRST_NAME"]).isEqualTo("Pebbles") 473 | assertThat(rows[1]["FIRST_NAME"]).isEqualTo("Bamm Bamm") 474 | } 475 | } 476 | 477 | companion object { 478 | const val JDBC_URL = "jdbc:hsqldb:mem:aname" 479 | const val JDBC_DRIVER = "org.hsqldb.jdbcDriver" 480 | } 481 | } 482 | --------------------------------------------------------------------------------