Bson没有声明@BsonProperty中声明的字段的正确名称

时间:2020-09-20 20:25:45

标签: mongodb kotlin bson

@BsonProperty(“ name”)在构造函数中不起作用

我的数据类代码

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()
    }

}

储值:

enter image description here

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

1 个答案:

答案 0 :(得分:1)

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

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()

    // ...
}

在注释属性或主要构造函数参数时,会从相应的Kotlin元素生成多个Java元素,因此在生成的Java字节码中有多个可能的注释位置。 -Annotation Use-site Targets

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

Spring Data Mongo数据库

如果您使用的是Spring Data Mongo DB,则Bson注释无效,但您可以简单地使用@Field注释。不需要@BsonCreator

相关问题