Reputation: 61
@BsonProperty("name") in constructor isn't working
My data class code
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()
}
}
Stored value:
The correct name of output field in mongo db should be "id_long" and not "idLong"
Upvotes: 0
Views: 1243
Reputation: 10681
A properly annotated class could look as follows:
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
@field:BsonProperty("id_long")
syntax.DiscordPunishment
class has no default constructor, you need the @BsonCreator
annotation.@BsonCreator
requires @BsonProperty
on each parameterSpring Data Mongo DB:
If you are using Spring Data Mongo DB, the Bson annotations have no effect, but you can simply use @Field annotation. The @BsonCreator
is not required.
Upvotes: 4