Global Config

This chapter will guide you on how to set up Kronos globally.

Use this table to choose the global settings to configure first.

LevelConfigureEntry
RequiredDefault data source wrapperDefault Data Source Settings
CommonTable and column naming, default date format, temporal time zone, loggingGlobal Table Name Strategy, Global Column Naming Strategy, Default Date Time Format, Temporal Time Zone, Log output path and switch
Enable by business needCommon field strategies, no-value behavior, JSON serialization, custom value mapping, map value conversionCreation Time Strategy, Logical Deletion Strategy, No-value strategy, 📚Serialization, Custom value mapping, Map value conversion

Compiler-plugin setup is configured in the build tool. See 📚Compiler Plugins for source-set and diagnostic checks.

Default Data Source Settings

Set Kronos.dataSource before running ORM operations. Operations without an explicit wrapper call this function to get the default data source.

The data source wrapper setup is covered in 📚Connect to DB.

default

import com.kotlinorm.Kronos
import com.kotlinorm.wrappers.KronosJdbcWrapper
import org.apache.commons.dbcp2.BasicDataSource

val wrapper = KronosJdbcWrapper(BasicDataSource())

Kronos.dataSource = { wrapper }

The Kronos.dataSource defaults to NoneDataSourceWrapper, be sure to modify your configuration file before using it.

Pass a wrapper to execute(wrapper) when one operation should use another data source.

operation wrapper

val archiveWrapper = KronosJdbcWrapper(archiveDataSource)

User(id = 1)
    .update()
    .set { it.name = "Kronos ORM" }
    .where()
    .execute(archiveWrapper)

Return different wrappers from Kronos.dataSource when the application chooses a data source at runtime.

dynamic

import com.kotlinorm.Kronos

Kronos.dataSource = {
    if (TenantContext.current() == "archive") archiveWrapper else primaryWrapper
}

Global Table Name Strategy

The table name strategy means that by default (no annotated configuration), kronos automatically generates a table name for the database based on the Kotlin class name, e.g. TbUser -> tb_user.

Parameters:

namedescriptiontypedefault
tableNamingStrategyGlobal Table Naming StrategyKronosNamingStrategyNoneNamingStrategy
Creating a custom table naming strategy `KronosNamingStrategy` is detailed in: 📚concept - Naming Strategy.

LineHumpNamingStrategy table names

This strategy converts kotlin class names to underscore-separated lowercase strings, e.g., ADataClass -> a_data_class, and database table/column names to camel names, e.g., user_name -> userName.

table

import com.kotlinorm.Kronos

Kronos.tableNamingStrategy = Kronos.lineHumpNamingStrategy

result

UserProfile -> user_profile

NoneNamingStrategy table names

NoneNamingStrategy leaves kotlin class names and database names unchanged. Kronos uses this strategy by default.

none

import com.kotlinorm.Kronos

Kronos.tableNamingStrategy = Kronos.noneNamingStrategy

none result

UserProfile -> UserProfile

Global Column Naming Strategy

Similar to the global table naming strategy, the column naming strategy refers to the default behavior where Kronos automatically generates column names based on the property names of Kotlin classes, for example: classId -> class_id.

Parameters:

namedescriptiontypedefault
fieldNamingStrategyGlobal Column Name StrategyKronosNamingStrategyNoneNamingStrategy

Use the same naming strategy for columns when Kotlin property names should map to database column names.

field

import com.kotlinorm.Kronos

Kronos.fieldNamingStrategy = Kronos.lineHumpNamingStrategy

field result

userName -> user_name

Creation Time Strategy

Used to set the creation time field for all tables.

Parameters:

namedescriptiontypedefault
createTimeStrategyCreate time strategy, including whether to enable, kotlin property name and database column name informationKronosCommonStrategyKronosCommonStrategy(enabled = false, field = Field("create_time", "createTime"))

Customize the creation of a time strategy by creating a KronosCommonStrategy, see: 📚concept - Common Strategy).

The global default for the creation time strategy is turned off and needs to be manually enabled.

Add the configured property to each model that uses this strategy. Field("create_time", "createTime") uses a createTime property.

create time

import com.kotlinorm.Kronos
import com.kotlinorm.beans.config.KronosCommonStrategy
import com.kotlinorm.beans.dsl.Field

Kronos.createTimeStrategy = KronosCommonStrategy(enabled = true, field = Field("create_time", "createTime"))

Configure @CreateTime on an individual model to override the global setting. See 📚Annotations.

Update Time Strategy

Used to set the update time field for all tables (whether to enable, Kotlin property name, and database column name).

Parameters:

namedescriptiontypedefault
updateTimeStrategyUpdate timing strategy, including whether to enable, kotlin property name, and database column name informationKronosCommonStrategyKronosCommonStrategy(enabled = false, field = Field("update_time", "updateTime"))

By creating a custom update strategy KronosCommonStrategy, see: 📚concept - Common Strategy).

The global default for update time strategy is turned off and needs to be manually enabled.

Add the configured property to each model that uses this strategy. Field("update_time", "updateTime") uses an updateTime property.

update time

import com.kotlinorm.Kronos
import com.kotlinorm.beans.config.KronosCommonStrategy
import com.kotlinorm.beans.dsl.Field

Kronos.updateTimeStrategy = KronosCommonStrategy(enabled = true, field = Field("update_time", "updateTime"))

Configure @UpdateTime on an individual model to override the global setting. See 📚Annotations.

Logical Deletion Strategy

Used to set the logical deletion strategy for all tables (whether to enable, Kotlin property name, and database column name).

Parameters:

namedescriptiontypedefault
logicDeleteStrategyLogical Deletion Strategy, including whether to enable, kotlin property name, and database column name informationKronosCommonStrategyKronosCommonStrategy(enabled = false, field = Field("deleted"))

By creating a custom logical deletion strategy KronosCommonStrategy, see: 📚concept - common strategy.

The global default for the logical delete strategy is turned off and needs to be manually enabled.

Add the configured property to each model that uses this strategy. Field("deleted") uses a deleted property.

logic delete

import com.kotlinorm.Kronos
import com.kotlinorm.beans.config.KronosCommonStrategy
import com.kotlinorm.beans.dsl.Field

Kronos.logicDeleteStrategy = KronosCommonStrategy(enabled = true, field = Field("deleted"))

logic delete sql

SELECT `id`, `name`, `deleted`
FROM `user`
WHERE `user`.`deleted` = 0

Configure @LogicDelete on an individual model to override the global setting. See 📚Annotations.

Optimistic Lock (Version) Strategy

Used to set the optimistic lock version field for all tables (whether it is on, kotlin attribute name and database column name).

Parameters:

namedescriptiontypedefault
optimisticLockStrategyOptimistic lock strategy, including whether to enable, kotlin property name, and database column name informationKronosCommonStrategyKronosCommonStrategy(enabled = false, field = Field("version"))

By creating a custom optimistic lock strategy KronosCommonStrategy, see: 📚concept - Common Strategy.

The global default for the optimistic lock strategy is turned off and needs to be manually enabled.

Add the configured property to each model that uses this strategy. Field("version") uses a version property.

version

import com.kotlinorm.Kronos
import com.kotlinorm.beans.config.KronosCommonStrategy
import com.kotlinorm.beans.dsl.Field

Kronos.optimisticLockStrategy = KronosCommonStrategy(enabled = true, field = Field("version"))

Configure @Version on an individual model to override the global setting. See 📚Annotations.

Default Date Time Format

Used to specify the default date-time formatting pattern. The default value is yyyy-MM-dd HH:mm:ss.

Parameters:

namedescriptiontypedefault
defaultDateFormatDefault Date Time FormatStringyyyy-MM-dd HH:mm:ss

Kronos uses yyyy-MM-dd HH:mm:ss to format the date/time by default, you can change the default format by the following ways:

format

import com.kotlinorm.Kronos

Kronos.defaultDateFormat = "yyyy-MM-dd HH:mm:ss"

Configure @DateTimeFormat on an individual model to override the global setting. See 📚Annotations.

Temporal Time Zone

Kronos.timeZone is one IANA time-zone id shared by the common API. Its default value is null, which uses the current platform's system default. JVM resolves the id with ZoneId; Native resolves it with kotlinx.datetime.TimeZone.

kotlin.time.Instant and the compatible kotlinx.datetime.Instant represent UTC instants. The configured zone is used only when automatic codec or time strategies convert an instant to a local calendar value. LocalDate, LocalDateTime, and LocalTime retain their timezone-free text semantics.

kotlin

import com.kotlinorm.Kronos

Kronos.timeZone = null              // platform system default
Kronos.timeZone = "UTC"
Kronos.timeZone = "Asia/Shanghai"

No-value strategy

Use .takeIf(...) to keep a predicate when a Kotlin condition is true, or .takeUnless(...) to keep it when the condition is false.

ignore

val name: String? = null

val users = User()
    .select()
    .where { (it.name == name).takeIf(name != null) }
    .toList()

The Boolean gate is ordinary Kotlin code. For example, (it.status == 0).takeUnless(includeInactive) omits the status predicate when includeInactive is true.

ignore sql

SELECT `id`, `name`
FROM `user`

Use == null or isNull when the generated condition should be SQL IS NULL.

is null

val users = User()
    .select()
    .where { it.name == null }
    .toList()

is null sql

SELECT `id`, `name`
FROM `user`
WHERE `user`.`name` IS NULL

Use NoValueStrategyType.Ignore with caution in DELETE and UPDATE operations to avoid full-table deletion or full-table updates.

For details, see 📚No-value Behavior.

Custom value mapping

Register a mapping at application startup when a model property uses a domain value such as Money and its column stores a scalar value. See 📚Custom Value Mapping for a complete Money example.

Use @Serialize with 📚Serialization for JSON objects and collections.

Log output path and switch

Used to set the path and switch for log output under global default conditions.

Parameters:

namedescriptiontypedefault
logging.enabledGlobal logging switchBooleantrue
logging.pathBundled output destinationsArray<String>["console"]
logging.typeLogger adapterKLoggerTypeDEFAULT_LOGGER

Write logs to the console and a file path by setting logging.path. The 📚Kronos-logging page covers output destinations and logger adapters.

console and file

import com.kotlinorm.Kronos

Kronos.logging.enabled = false
// Re-enable output with the existing configuration.
Kronos.logging.enabled = true
Kronos.logging.path = ["console", "/var/log/kronos"]

Map value conversion

Use safeMapperTo to create a new model from application input, and use safeFromMapData to apply input to a model that already exists. Both APIs match map keys with model properties and convert compatible values. See 📚Map/KPojo Conversion for the complete map-to-model and model-to-model API reference.

import com.kotlinorm.interfaces.KPojo
import com.kotlinorm.utils.Extensions.safeMapperTo

data class User(
    var id: Int? = null,
    var name: String? = null,
) : KPojo

val input = mapOf("id" to 1L, "name" to "Kronos")

val created = input.safeMapperTo<User>()
// User(id = 1, name = "Kronos")

val updated = User().safeFromMapData<User>(input)
// User(id = 1, name = "Kronos")

Set strictSetValue = true for an input boundary that receives already-normalized values. With this setting, built-in numeric, boolean, and date/time values are accepted when they match the model property type. Registered custom mappings remain available. For example, User.id: Int? accepts an Int input and reports a mapping error for a Long input.

import com.kotlinorm.Kronos

Kronos.strictSetValue = true