表与列

指定表名和列名

数据库表名需要明确指定时,在 KPojo 类上使用 @Table。数据库列名需要和 Kotlin 属性名不同时,在属性上使用 @Column。这些注解的优先级高于 📚命名策略。

model

import com.kotlinorm.annotations.Column
import com.kotlinorm.annotations.ColumnType
import com.kotlinorm.annotations.CreateTime
import com.kotlinorm.annotations.Default
import com.kotlinorm.annotations.NonNull
import com.kotlinorm.annotations.PrimaryKey
import com.kotlinorm.annotations.Table
import com.kotlinorm.annotations.UpdateTime
import com.kotlinorm.enums.KColumnType
import com.kotlinorm.interfaces.KPojo
import java.time.LocalDateTime

@Table("tb_account")
data class Account(
    @PrimaryKey(identity = true)
    var id: Int? = null,
    @Column("user_name")
    @ColumnType(KColumnType.VARCHAR, length = 80)
    @NonNull
    var username: String? = null,
    @Default("0")
    var loginCount: Int? = null,
    @CreateTime
    var createdAt: LocalDateTime? = null,
    @UpdateTime
    var updatedAt: LocalDateTime? = null
) : KPojo

表元数据形态如下:

Kotlin 属性数据库列DDL 行为
idid主键自增列。
usernameuser_nameVARCHAR(80) NOT NULL。
loginCountloginCount默认值 0。
createdAtcreatedAt创建时间策略填充的字段。
updatedAtupdatedAt更新时间策略填充的字段。

非空和默认值

表 DDL 中,属性默认可空;主键字段或使用 @NonNull 的字段会生成非空约束。@Default 中填写数据库默认值表达式。

MySQL

CREATE TABLE IF NOT EXISTS `tb_account` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `user_name` VARCHAR(80) NOT NULL,
    `loginCount` INT DEFAULT 0,
    `createdAt` DATETIME,
    `updatedAt` DATETIME
)

字符串字面量默认值需要把引号写进注解值:

default

@Default("'active'")
var status: String? = null

default sql

`status` VARCHAR(255) DEFAULT 'active'

创建时间和更新时间

需要在插入、更新或 upsert 时写入当前时间的属性,可以使用 @CreateTime 和 @UpdateTime。

timestamps

@Table("tb_account")
data class AccountTime(
    @PrimaryKey(identity = true)
    var id: Int? = null,
    @CreateTime
    var createdAt: LocalDateTime? = null,
    @UpdateTime
    var updatedAt: LocalDateTime? = null
) : KPojo

插入参数形态:

insert params

createdAt -> 2026-07-06T10:15:30
updatedAt -> 2026-07-06T10:15:30

更新参数形态:

update params

updatedAt -> 2026-07-06T10:20:00

完整注解参数见 📚注解,Kotlin 类型推断见 📚列类型,表索引映射见 📚索引。