MyBatis Dynamic SQL with Kotlin Usage Notes

This page is a short introduction to using the classes generated for the MyBatis3Kotlin runtime These classes are dependent on the MyBatis Dynamic SQL library version 1.1.4 or higher. Please refer to that site for full information about how the library works. In particular, see the Kotlin Usage Page for full details.

Generated Files

For each introspected table, the generator will generate three Kotlin files:

  1. A Kotlin data class that represents a row in the table. By default, the class will be named based on the table name
  2. A "support" class that includes a table definition and column definitions for the database table
  3. A mapper interface with the basic MyBatis mapper methods and extension methods that simplify reuse of the basic mapper methods. This is similar to the default interface methods generated in the other runtimes, but it is accomplished with extension methods in Kotlin.

Important notes about the generated objects:

  • No XML is generated
  • No separate "Example" class is generated
  • There are no separate "with BLOBs" and "without BLOBs" methods. If your table includes BLOB fields, then they are included in all operations.
  • Model classes are always generated in the "flat" model meaning there is no separate primary key class or BLOBs class
  • Java 8 or higher is required
  • Any recent version of Kotlin should work
  • MyBatis 3.4.2 or higher is required
  • MyBatis Dynamic SQL 1.4.0 or higher is required

Format of the "Support" classes

A "support" class is created for each table. The support class includes a definition of the table and all the columns in the table. These items are used as input to the code generated in the mappers - most often for the where clauses you will write.

For example, suppose there is a table "TABLE_CODE" in schema "MYSCHEMA". Further suppose that table has "ID" and "DESCRIPTION" columns. The generated support class will look like this:

package example

import java.sql.JDBCType
import org.mybatis.dynamic.sql.AliasableSqlTable
import org.mybatis.dynamic.sql.util.kotlin.elements.column

object TableCodeDynamicSqlSupport {
    val tableCode = TableCode()
    val id = tableCode.id
    val description = tableCode.description

    class TableCode : AliasableSqlTable<TableCode>("MYSCHEMA.TABLE_CODE", ::TableCode) {
        val id = column<Int>(name = "ID", jdbcType = JDBCType.INTEGER)
        val description = column<String>(name = "DESCRIPTION", jdbcType = JDBCType.VARCHAR)
    }
}

In your code you can import that table object and/or each generated column (Kotlin does not support a star "*" import in this case). With these imports you can refer to the fields in either a direct or qualified manner - "id" or "tableCode.id".

Usage of the Mapper Classes

The following methods work the same as the other runtimes and we won't cover them here:

  • deleteByPrimaryKey
  • insert - insert a single row (will insert nulls)
  • insertMultiple - insert multiple rows (will insert nulls)
  • insertSelective - insert a single row and ignore null properties
  • selectByPrimaryKey
  • updateByPrimaryKey - will set null values
  • updateByPrimaryKey Selective - ignores null values

There are no "by example" methods. Instead, there are general purpose methods that allow you to specify a where clause with a lambda. The generator will create the following general methods:

  • count
  • delete
  • select
  • selectDistinct
  • selectOne
  • update

Each of these methods includes support for a very flexible WHERE clause that can be specified with a lambda. If you don't need a where clauses, there are utility functions that mean "all rows".

For example, you can retrieve the total number of rows in a table by calling the count method without a WHERE clause. That code looks like this:

  val totalRows = mapper.count { allRows() }

You can retrieve all rows in a table by calling select without a WHERE clause like this:

  val allRecords = mapper.select { allRows() }

It is far more interesting to add WHERE clauses to these methods. To add support for WHERE clauses, you should import the elements from the support class as shown above, and you should also import the SqlBuilder support. Then you can code arbitrarily complex where clauses, and "ORDER BY" phrases as shown below:

// import the generated "support" items...
import example.TableCodeDynamicSqlSupport.description
import example.TableCodeDynamicSqlSupport.id

class SomeService {

    fun simpleWhere() {
        ...
        // Simple WHERE clause
        val records = mapper.select {
            where { id isEqualTo 3 }
        }
        ...
    }

    fun complexWhere1() {
        ...
        // Simple WHERE clause with OR
        val records = mapper.select {
            where { id isEqualTo 3 }
            or { description isLike "f%" }
        }
        ...
    }

    fun complexWhere2() {
        ...
        // complex WHERE and ORDER BY
        val records = mapper.select {
            where {
                id isLessThan 10
                and { description isEqualTo "foo" }
            }
            or { description isLike "b%" }
            orderBy(id.descending())
        }
        ...
    }
}

Update Method Usage

The generated update statement is very flexible. You can now create any arbitrary update, as well as updates that mimic the old updateByExample and updateByExampleSelective methods.

// import the generated "support" items...
import example.TableCodeDynamicSqlSupport.description
import example.TableCodeDynamicSqlSupport.id

class SomeService {

    fun simpleUpdate() {
        ...
        // Flexible update - no backing record needed
        val rows = mapper.update {
            set(id) equalTo 1
            set(description).equalToNull()
            where { id isEqualTo 3 }
        }
        ...
    }

    fun updateByExample(row: TableCode) {
        ...
        // Update like the old updateByExample method
        val rows =  mapper.update {
            updateAllColumns(row)
            where { id isEqualTo 3 }
            or { description isLike "f%" }
        }
        ...
    }

    fun updateByExampleSelective(row: TableCode) {
        ...
        // Update like the old updateByExampleSelective method
        val rows =  mapper.update {
            updateSelectiveColumns(row)
            where { id isEqualTo 3 }
            or { description isLike "f%" }
        }
        ...
    }
}

New Plugins

Because the *ByExample methods are not generated, it no longer makes sense to control method generation via the properties on an XML <table> configuration like enableInsert, enableSelectByExample, etc. So this new runtime will ignore any of those properties. If you wish to have this level of control over what is generated, you can accomplish that with a plugin. We have also included the following plugins for general use with this runtime:

  • org.mybatis.generator.plugins.dsql.DisableDeletePlugin - disables all generated delete methods
  • org.mybatis.generator.plugins.dsql.DisableInsertPlugin - disables all generated insert methods
  • org.mybatis.generator.plugins.dsql.DisableUpdatePlugin - disables all generated update methods
  • org.mybatis.generator.plugins.dsql.ReadOnlyPlugin - disables all generated delete, insert, and update methods