@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()
}
}
储值:
mongo db中输出字段的正确名称应该是“ id_long”而不是“ idLong”
答案 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
@field:BsonProperty("id_long")
语法。DiscordPunishment
类没有默认构造函数,因此需要@BsonCreator
批注。@BsonCreator
在每个参数上需要@BsonProperty
Spring Data Mongo数据库:
如果您使用的是Spring Data Mongo DB,则Bson注释无效,但您可以简单地使用@Field注释。不需要@BsonCreator
。