编辑此页面

简化的 MongoDB with Panache 和 Kotlin

MongoDB 是一个广为人知的 NoSQL 数据库,得到了广泛应用。MongoDB with Panache 在这个熟悉的框架之上提供了一个新的层。本指南不会深入探讨这两者的细节,因为这些细节已在MongoDB with Panache 指南中涵盖。在本指南中,我们将介绍在基于 Kotlin 的 Quarkus 应用程序中使用 MongoDB with Panache 所需的特定 Kotlin 更改。

首先:一个例子

正如我们在 MongoDB with Panache 指南中所见,它允许我们通过一些自动提供的功能来扩展实体和存储库(也称为 DAO)的功能。使用 Kotlin 时,其方法与 Java 版本非常相似,只有一两个细微的更改。要为实体启用 Panache,可以将其定义为如下所示:

class Person: PanacheMongoEntity {
    lateinit var name: String
    lateinit var birth: LocalDate
    lateinit var status: Status
}

正如你所见,我们的实体保持简单。但是,与 Java 版本相比,有一个细微的差别。Kotlin 语言不支持 Java 所具有的静态方法概念。相反,我们必须使用伴生对象

class Person : PanacheMongoEntity() {
    companion object: PanacheMongoCompanion<Person> {  (1)
        fun findByName(name: String) = find("name", name).firstResult()
        fun findAlive() = list("status", Status.Alive)
        fun deleteStefs() = delete("name", "Stef")
    }

    lateinit var name: String  (2)
    lateinit var birth: LocalDate
    lateinit var status: Status
}
1 伴生对象包含所有与特定实例无关的方法,从而允许对特定类型进行通用管理和查询。
2 这里有几种选择,但我们选择了 lateinit 方法。这使我们可以将这些字段声明为非空,因为它们将由构造函数(未显示)或由 MongoDB POJO 编解码器从数据库加载数据来正确赋值。
这些类型与那些教程中提到的 Java 类型不同。对于 Kotlin 支持,所有 Panache 类型都位于 io.quarkus.mongodb.panache.kotlin 包中。这个子包允许区分 Java 和 Kotlin 变体,并允许在一个项目中无歧义地使用两者。

在 Kotlin 版本中,我们将大部分活动记录模式功能移到了 伴生对象中。除了这个细微的更改之外,我们还可以以易于从 Java 世界映射的方式使用我们的类型。

使用存储库模式

定义您的实体

使用存储库模式时,可以将实体定义为常规 POJO。

class Person {
    var id: ObjectId? = null; // used by MongoDB for the _id field
    lateinit var name: String
    lateinit var birth: LocalDate
    lateinit var status: Status
}

定义您的存储库

使用存储库时,通过让它们实现 PanacheMongoRepository,可以获得与活动记录模式完全相同的便捷方法,这些方法将被注入到你的存储库中。

@ApplicationScoped
class PersonRepository: PanacheMongoRepository<Person> {
     fun findByName(name: String) = find("name", name).firstResult()
     fun findAlive() = list("status", Status.Alive)
     fun deleteStefs() = delete("name", "Stef")
}

PanacheMongoEntityBase 上定义的所有操作都可以在你的存储库上使用,因此使用方式与活动记录模式完全相同,只是你需要注入它。

@Inject
lateinit var personRepository: PersonRepository

@GET
fun count() = personRepository.count()

最有用的操作

编写存储库后,以下是您可以执行的最常见的操作

// creating a person
var person = Person()
person.name = "Stef"
person.birth = LocalDate.of(1910, Month.FEBRUARY, 1)
person.status = Status.Alive

// persist it: if you keep the default ObjectId ID field, it will be populated by the MongoDB driver
personRepository.persist(person)

person.status = Status.Dead;

// Your must call update() in order to send your entity modifications to MongoDB
personRepository.update(person);


// delete it
personRepository.delete(person);

// getting a list of all Person entities
val allPersons = personRepository.listAll()

// finding a specific person by ID
// here we build a new ObjectId, but you can also retrieve it from the existing entity after being persisted
ObjectId personId = new ObjectId(idAsString);
person = personRepository.findById(personId) ?: throw Exception("No person with that ID")

// finding all living persons
val livingPersons = personRepository.list("status", Status.Alive)

// counting all persons
val countAll = personRepository.count()

// counting all living persons
val countAlive = personRepository.count("status", Status.Alive)

// delete all living persons
personRepository.delete("status", Status.Alive)

// delete all persons
personRepository.deleteAll()

// delete by id
val deleted = personRepository.deleteById(personId)

// set the name of all living persons to 'Mortal'
var updated = personRepository.update("name", "Mortal").where("status", Status.Alive)

所有 list 方法都有等效的 stream 版本。

val persons = personRepository.streamAll();
val namesButEmmanuels = persons
    .map { it.name.toLowerCase() }
    .filter { it != "emmanuel" }

有关更多示例,请查阅Java 版本以获取完整详细信息。两种 API 相同且工作方式相同,除了 Kotlin 特定的调整,让 Kotlin 开发人员感觉更自然。这些调整包括更好地利用可空性和 API 方法中没有 Optional

设置和配置 MongoDB with Panache

要开始使用 Kotlin 和 MongoDB with Panache,通常可以遵循 Java 教程中的步骤。配置项目最大的变化是需要包含的 Quarkus 伪指令。当然,如果需要,可以保留 Java 版本,但如果你只需要 Kotlin API,则包含以下依赖项:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-mongodb-panache-kotlin</artifactId>  (1)
</dependency>
1 注意末尾添加了 -kotlin。通常你只需要这个版本,但如果你的项目将同时使用 Java 和 Kotlin 代码,你可以安全地同时包含这两个伪指令。
build.gradle
implementation("io.quarkus:quarkus-mongodb-panache-kotlin") (1)
1 注意末尾添加了 -kotlin。通常你只需要这个版本,但如果你的项目将同时使用 Java 和 Kotlin 代码,你可以安全地同时包含这两个伪指令。

相关内容