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.
| Level | Configure | Entry |
|---|---|---|
| Required | Default data source wrapper | Default Data Source Settings |
| Common | Table and column naming, default date format, temporal time zone, logging | Global Table Name Strategy, Global Column Naming Strategy, Default Date Time Format, Temporal Time Zone, Log output path and switch |
| Enable by business need | Common field strategies, no-value behavior, JSON serialization, custom value mapping, map value conversion | Creation 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.dataSourcedefaults toNoneDataSourceWrapper, 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:
| name | description | type | default |
|---|---|---|---|
tableNamingStrategy | Global Table Naming Strategy | KronosNamingStrategy | NoneNamingStrategy |
📚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.lineHumpNamingStrategyresult
UserProfile -> user_profileNoneNamingStrategy 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.noneNamingStrategynone result
UserProfile -> UserProfileGlobal 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:
| name | description | type | default |
|---|---|---|---|
fieldNamingStrategy | Global Column Name Strategy | KronosNamingStrategy | NoneNamingStrategy |
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.lineHumpNamingStrategyfield result
userName -> user_nameCreation Time Strategy
Used to set the creation time field for all tables.
Parameters:
| name | description | type | default |
|---|---|---|---|
createTimeStrategy | Create time strategy, including whether to enable, kotlin property name and database column name information | KronosCommonStrategy | KronosCommonStrategy(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
@CreateTimeon 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:
| name | description | type | default |
|---|---|---|---|
updateTimeStrategy | Update timing strategy, including whether to enable, kotlin property name, and database column name information | KronosCommonStrategy | KronosCommonStrategy(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
@UpdateTimeon 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:
| name | description | type | default |
|---|---|---|---|
logicDeleteStrategy | Logical Deletion Strategy, including whether to enable, kotlin property name, and database column name information | KronosCommonStrategy | KronosCommonStrategy(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` = 0Configure
@LogicDeleteon 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:
| name | description | type | default |
|---|---|---|---|
optimisticLockStrategy | Optimistic lock strategy, including whether to enable, kotlin property name, and database column name information | KronosCommonStrategy | KronosCommonStrategy(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
@Versionon 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:
| name | description | type | default |
|---|---|---|---|
defaultDateFormat | Default Date Time Format | String | yyyy-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
@DateTimeFormaton 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 NULLUse
NoValueStrategyType.Ignorewith caution inDELETEandUPDATEoperations 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:
| name | description | type | default |
|---|---|---|---|
logging.enabled | Global logging switch | Boolean | true |
logging.path | Bundled output destinations | Array<String> | ["console"] |
logging.type | Logger adapter | KLoggerType | DEFAULT_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