在Kotlin中操作数据库:PostgreSQL与MongoDB

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

简介:为什么用Kotlin处理数据库?

Kotlin是一种现代静态类型语言,与Java完全兼容,广泛用于后端应用开发。凭借简洁的语法、空安全性和强大的工具,Kotlin非常适合处理关系型数据库(PostgreSQL)和文档型数据库(MongoDB)。本文将介绍连接、执行CRUD操作和优化查询的实际示例。

我们将介绍两个流行的库:Exposed(用于PostgreSQL)和KMongo(用于MongoDB)。您将学习如何配置环境、编写高效查询以及避免常见错误。

1. 通过Exposed使用PostgreSQL

Exposed是Kotlin的ORM库,提供两种API:DSL(领域特定语言)用于编写SQL风格的查询,以及DAO(数据访问对象)用于面向对象的方法。下面介绍这两种方式。

1.1. 连接与配置

在build.gradle.kts中添加依赖:

dependencies {
    implementation("org.jetbrains.exposed:exposed-core:0.41.1")
    implementation("org.jetbrains.exposed:exposed-dao:0.41.1")
    implementation("org.jetbrains.exposed:exposed-jdbc:0.41.1")
    implementation("org.postgresql:postgresql:42.5.0")
}

连接数据库:

import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.transactions.transaction

fun main() {
    Database.connect(
        url = "jdbc:postgresql://localhost:5432/mydb",
        driver = "org.postgresql.Driver",
        user = "user",
        password = "password"
    )
    println("已连接到PostgreSQL")
}

1.2. 创建表与CRUD操作(DSL)

定义Users表:

import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.update

object Users : Table() {
    val id = integer("id").autoIncrement()
    val name = varchar("name", 50)
    val email = varchar("email", 100).uniqueIndex()
    override val primaryKey = PrimaryKey(id)
}

执行CRUD操作:

transaction {
    // 创建表
    SchemaUtils.create(Users)

    // INSERT
    Users.insert {
        it[name] = "阿列克谢"
        it[email] = "alex@example.com"
    }

    // SELECT
    val users = Users.selectAll().map {
        "${it[Users.id]}: ${it[Users.name]} (${it[Users.email]})"
    }
    println(users)

    // UPDATE
    Users.update({ Users.id eq 1 }) {
        it[name] = "阿列克谢·伊万诺夫"
    }

    // DELETE(使用deleteWhere)
    Users.deleteWhere { Users.id eq 2 }
}

1.3. DAO方式

创建实体和DAO类:

import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable

object UsersDAO : IntIdTable() {
    val name = varchar("name", 50)
    val email = varchar("email", 100)
}

class User(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<User>(UsersDAO)
    var name by UsersDAO.name
    var email by UsersDAO.email
}

// 使用
transaction {
    val newUser = User.new {
        name = "玛丽亚"
        email = "maria@example.com"
    }
    println("已创建用户,ID为:${newUser.id.value}")
}

2. 通过KMongo使用MongoDB

KMongo是一个基于官方Java驱动构建的协程导向MongoDB驱动。它支持通过kotlinx.serialization和Jackson进行序列化。

2.1. 连接KMongo

在build.gradle.kts中添加:

博客

书籍推荐