Bson 未声明在@BsonProperty 中声明的字段的正确名称

Bson not declaring correct name of field declared in @BsonProperty

构造函数中的@BsonProperty("name") 不工作

我的数据class代码

package net.hyren.discord.bot.misc.punish.data

import org.bson.codecs.pojo.annotations.BsonIgnore
import org.bson.codecs.pojo.annotations.BsonProperty

/**
 * @author SrGutyerrez
 **/
data class DiscordPunishment(
        @BsonProperty(value = "id_long") val idLong: Long,
        val duration: Long
) {

    @BsonIgnore
    fun isActive(): Boolean = this.duration >= System.currentTimeMillis()

    override fun equals(other: Any?): Boolean {
        if (this === other) return true

        if (javaClass != other?.javaClass) return false

        other as DiscordPunishment

        if (idLong != other.idLong) return false

        return true
    }

    override fun hashCode(): Int {
        return idLong.hashCode()
    }

}

存储值:

mongo 数据库中输出字段的正确名称应该是“id_long”而不是“idLong”

正确注释的 class 可能如下所示:

data class DiscordPunishment @BsonCreator constructor(
        @param:BsonProperty("id_long")
        @field:BsonProperty("id_long")
        val idLong: Long,
        @param:BsonProperty("duration")
        val duration: Long
) {

    @BsonIgnore
    fun isActive(): Boolean = this.duration >= System.currentTimeMillis()

    // ...
}

When you're annotating a property or a primary constructor parameter, there are multiple Java elements which are generated from the corresponding Kotlin element, and therefore multiple possible locations for the annotation in the generated Java bytecode. - Annotation Use-site Targets

  1. 在您的情况下,注释必须出现在字段中(或 getter),因此您需要使用 @field:BsonProperty("id_long") 语法。
  2. 由于 DiscordPunishment class 没有默认构造函数,您需要 @BsonCreator 注解。
  3. @BsonCreator 每个参数需要 @BsonProperty

Spring数据Mongo数据库:

如果你使用的是Spring数据Mongo数据库,Bson注解是没有作用的,你可以简单的使用@Field注解。 @BsonCreator 不是必需的。