Database First
Generate KPojo classes from an existing schema
Use Database First when database tables already exist and the Kotlin model should follow that schema. In Kronos, this workflow is handled by 📚Code Generator: read JDBC metadata, select tables in config.toml, and write Kotlin KPojo files from a Kotlin Script template.
Start with a table that is already managed by the database team.
mysql
CREATE TABLE tb_user (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(64) NOT NULL,
email VARCHAR(128),
create_time DATETIME,
update_time DATETIME,
deleted BIT DEFAULT 0,
version INT
);Select tables and output
Create config.toml. The [[table]] list chooses which database tables become Kotlin files. targetDir and packageName decide where the generated source is written.
config.toml
[[table]]
name = "tb_user"
className = "User"
[output]
targetDir = "src/main/kotlin/com/example/entity"
packageName = "com.example.entity"
tableCommentLineWords = 80With this configuration, the generator writes one file.
generated files
src/main/kotlin/com/example/entity/User.ktConfigure metadata reading
The dataSource section creates the JDBC connection used by Codegen. This example uses Apache DBCP2 and the built-in KronosJdbcWrapper.
config.toml
[dataSource]
wrapperClassName = "com.kotlinorm.wrappers.KronosJdbcWrapper"
dataSourceClassName = "org.apache.commons.dbcp2.BasicDataSource"
url = "jdbc:mysql://localhost:3306/kronos_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false"
username = "root"
password = "your_password"
driverClassName = "com.mysql.cj.jdbc.Driver"
initialSize = 5
maxTotal = 10Use the property names supported by the selected DataSource class. Add the matching JDBC driver and connection pool dependency in the script.
Map database names to KPojo fields
Use lineHumpNamingStrategy when underscore table or column names should become camel-case Kotlin names. Strategy fields generate Kronos annotations when matching columns are present.
config.toml
[strategy]
tableNamingStrategy = "lineHumpNamingStrategy"
fieldNamingStrategy = "lineHumpNamingStrategy"
primaryKeyStrategy = "id"
createTimeStrategy = "create_time"
updateTimeStrategy = "update_time"
logicDeleteStrategy = "deleted"
optimisticLockStrategy = "version"For the tb_user table above, create_time becomes createTime, and matching strategy columns receive the corresponding Kronos annotations.
User.kt
package com.example.entity
import com.kotlinorm.annotations.CreateTime
import com.kotlinorm.annotations.Default
import com.kotlinorm.annotations.LogicDelete
import com.kotlinorm.annotations.NonNull
import com.kotlinorm.annotations.PrimaryKey
import com.kotlinorm.annotations.Table
import com.kotlinorm.annotations.UpdateTime
import com.kotlinorm.annotations.Version
import com.kotlinorm.interfaces.KPojo
@Table("tb_user")
data class User(
@PrimaryKey(identity = true)
var id: Int? = null,
@NonNull
var username: String? = null,
var email: String? = null,
@CreateTime
var createTime: java.time.LocalDateTime? = null,
@UpdateTime
var updateTime: java.time.LocalDateTime? = null,
@LogicDelete
@Default("0") // @Default("false") for Postgres
var deleted: Boolean? = null,
@Version
var version: Int? = null
) : KPojoFor annotation behavior in insert, update, delete, and query operations, see 📚Annotation Config.
Run the generator
Create example.main.kts and add the Kronos artifacts, JDBC driver, and connection pool. The template below writes a compact KPojo class for every configured table.
example.main.kts
#!/usr/bin/env kotlin
@file:Repository("https://repo1.maven.org/maven2")
@file:DependsOn("com.kotlinorm:kronos-codegen:0.4.0")
@file:DependsOn("com.kotlinorm:kronos-core:0.4.0")
@file:DependsOn("com.kotlinorm:kronos-jdbc-wrapper:0.4.0")
@file:DependsOn("org.apache.commons:commons-dbcp2:<latest-stable>")
@file:DependsOn("com.mysql:mysql-connector-j:<latest-stable>")
import com.kotlinorm.codegen.KronosConfig.Companion.write
import com.kotlinorm.codegen.TemplateConfig.Companion.template
import com.kotlinorm.codegen.init
import com.kotlinorm.codegen.kotlinType
init("config.toml")
template {
+"package $packageName"
+""
+imports.joinToString("
") { "import $it" }
+""
+indexes.toAnnotations()
+"""@Table("$tableName")"""
+"""data class $className("""
+fields.mapIndexed { index, field ->
val annotations = field.annotations().joinToString("
") { "${indent(4)}$it" }
val annotationBlock = if (annotations.isEmpty()) "" else "$annotations
"
val comma = if (index == fields.lastIndex) "" else ","
"""$annotationBlock${indent(4)}var ${field.name}: ${field.kotlinType}? = null$comma"""
}.joinToString("
")
+") : KPojo"
}.write()Run the script with kotlinc -script.
shell
kotlinc -script example.main.ktsAfter a successful run, Codegen logs each written file.
output
File generated successfully: src/main/kotlin/com/example/entity/User.ktKeep generated KPojo files aligned
When the database schema changes, update config.toml if the table list, output package, or naming strategy changes, then rerun the script. Review the generated Kotlin source before committing it.
workflow
1. Apply the database schema change.
2. Run kotlinc -script example.main.kts.
3. Review generated KPojo files.
4. Use the generated KPojo in Kronos queries and mutations.For the full template API, config inheritance, column metadata annotations, and index generation, see 📚Code Generator. For applying schema changes from KPojo metadata, see 📚Schema Sync.