Gutyerrez
Gutyerrez

Reputation: 61

Bson not declaring correct name of field declared in @BsonProperty

@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:

enter image description here

The correct name of output field in mongo db should be "id_long" and not "idLong"

Upvotes: 0

Views: 1243

Answers (1)

Mafor
Mafor

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

  1. In your case, the annotation has to be present on the field (or getter), so you need to use @field:BsonProperty("id_long") syntax.
  2. As the DiscordPunishment class has no default constructor, you need the @BsonCreator annotation.
  3. @BsonCreator requires @BsonProperty on each parameter

Spring 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

Related Questions