提供 Kotlin 中使用 Exposed ORM 的查询、事务、迁移与仓储模式实践。
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "kotlin-exposed-patterns" 技能: 1. 下载 https://raw.githubusercontent.com/affaan-m/ECC/main/skills/kotlin-exposed-patterns/SKILL.md 2. 保存为 ~/.claude/skills/kotlin-exposed-patterns/SKILL.md 3. 装好后重载技能,告诉我可以用了
请给我一个 Kotlin Exposed DSL 示例:按用户 UUID 查询单个用户,并在协程安全的事务中返回可空结果。
一段使用 Exposed DSL、where 条件和 suspended transaction 的 Kotlin 查询示例。
请生成一个 Kotlin DatabaseFactory 示例,使用 HikariCP 配置 PostgreSQL 连接池,包括 driver、jdbcUrl、用户名、密码和最大连接数。
一个包含 HikariConfig 与 Database.connect 的数据库初始化代码示例。
请写一个 Kotlin 函数,在应用启动时运行 Flyway 迁移,数据源来自数据库配置,并使用 classpath:db/migration 目录。
一段调用 Flyway.configure、设置数据源与迁移目录的启动代码。
开发者在新建后端服务时,可用该技能快速组织 Exposed 的 DSL、DAO、事务与连接池配置,形成可投入生产的数据库访问结构。
当团队需要管理数据库 schema 变更时,可参考其中的 Flyway 模式,在启动阶段执行版本化迁移脚本并保持结构同步。
在需要提高可测试性和解耦程度时,可将 Exposed 查询封装在 repository 接口后面,并结合内存 H2 数据库进行测试。
文档概述了在 Kotlin 项目中使用 JetBrains Exposed ORM 的一套数据库访问实践,重点包括 DSL 与 DAO 两种查询方式、基于 newSuspendedTransaction 的事务处理、HikariCP 连接池配置、Flyway 迁移执行,以及通过 repository 模式解耦业务逻辑与数据层,并提到可结合 H2 进行测试。
Comprehensive patterns for database access with JetBrains Exposed ORM, including DSL queries, DAO, transactions, and production-ready configuration.
Exposed provides two query styles: DSL for direct SQL-like expressions and DAO for entity lifecycle management. HikariCP manages a pool of reusable database connections configured via HikariConfig. Flyway runs versioned SQL migration scripts at startup to keep the schema in sync. All database operations run inside newSuspendedTransaction blocks for coroutine safety and atomicity. The repository pattern wraps Exposed queries behind an interface so business logic stays decoupled from the data layer and tests can use an in-memory H2 database.
suspend fun findUserById(id: UUID): UserRow? =
newSuspendedTransaction {
UsersTable.selectAll()
.where { UsersTable.id eq id }
.map { it.toUser() }
.singleOrNull()
}
suspend fun createUser(request: CreateUserRequest): User =
newSuspendedTransaction {
UserEntity.new {
name = request.name
email = request.email
role = request.role
}.toModel()
}
val hikariConfig = HikariConfig().apply {
driverClassName = config.driver
jdbcUrl = config.url
username = config.username
password = config.password
maximumPoolSize = config.maxPoolSize
isAutoCommit = false
transactionIsolation = "TRANSACTION_READ_COMMITTED"
validate()
}
// DatabaseFactory.kt
object DatabaseFactory {
fun create(config: DatabaseConfig): Database {
val hikariConfig = HikariConfig().apply {
driverClassName = config.driver
jdbcUrl = config.url
username = config.username
password = config.password
maximumPoolSize = config.maxPoolSize
isAutoCommit = false
transactionIsolation = "TRANSACTION_READ_COMMITTED"
validate()
}
return Database.connect(HikariDataSource(hikariConfig))
}
}
data class DatabaseConfig(
val url: String,
val driver: String = "org.postgresql.Driver",
val username: String = "",
val password: String = "",
val maxPoolSize: Int = 10,
)
// FlywayMigration.kt
fun runMigrations(config: DatabaseConfig) {
Flyway.configure()
.dataSource(config.url, config.username, config.password)
.locations("classpath:db/migration")
.baselineOnMigrate(true)
.load()
.migrate()
}
// Application startup
fun Application.module() {
val config = DatabaseConfig(
url = environment.config.property("database.url").getString(),
username = environment.config.property("database.username").getString(),
password = environment.config.property("database.password").getString(),
)
runMigrations(config)
val database = DatabaseFactory.create(config)
// ...
}
-- src/main/resources/db/migration/V1__create_users.sql
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
role VARCHAR(20) NOT NULL DEFAULT 'USER',
metadata JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_role ON users(role);
…
它围绕 JetBrains Exposed ORM 的常见实践展开,包括 DSL 查询、DAO 模式、事务处理、HikariCP 连接池、Flyway 迁移以及 repository 模式。
文档节选指出数据库操作运行在 newSuspendedTransaction 代码块中,以支持协程安全和原子性。
有。文档节选提到 repository 模式有助于解耦业务逻辑,并可在测试中使用内存 H2 数据库。更多细节见源码仓库。
帮助开发者为具备交易权限的智能代理设计安全防护与风控机制
提供适用于 React/Next.js 的高质量动画模式,快速实现常见交互动效。
用于多轮推演与递归决策,保留可追溯证据链并比较多种方案。
用于 Laravel 项目的环境检查、测试、安全扫描与发布验收
端到端编排新功能开发流程,覆盖调研、规划、测试驱动实现、评审与提交把关。
帮助你编写或审查符合 React 18/19 最佳实践的组件与架构。
提供地道 Kotlin 模式与最佳实践,帮助构建健壮高效且易维护的应用。
帮助开发者快速掌握 Kotlin Ktor 服务端常用架构与测试模式。
帮助开发者掌握 Kotlin 协程与 Flow 在 Android 和 KMP 中的实战模式。
帮助开发者掌握 DAT SDK Android 的 Kotlin 约定、结果处理与会话能力规范。
提供面向生产后端的 MySQL 与 MariaDB 设计、查询与运维模式建议。
提供 PostgreSQL 查询优化、模式设计、索引与安全实践建议