Julieta
Julieta

Reputation: 427

Kotlin getter override + MongoDB

I'm new to Kotlin development and I cannot figure out how to deal with this issue. I have the following Kotlin data class mapped to a MongoDB collection (Spring Data MongoDB):

@Document(collection = "orders")
data class OrderEntity
@PersistenceConstructor
constructor(@Id val id: ObjectId? = null, val place: String, var date: Date,
            val closed: Boolean = false, val price: Int = 0)

I want to override the default id getter and return a string instead of an ObjectId. It seems that "id" field name cannot be changed because I'm getting the message "Customizing field name for id property not allowed! Custom name will not be considered!" so I can't use the _id solution that is always suggested.

How could one achieve this? Am I missing something?

Upvotes: 0

Views: 874

Answers (1)

Ryba
Ryba

Reputation: 1299

I haven't kept up to the latest and greates spring-data-mongo changes but if you simply change your id to be of type String? instead of ObjectId and your string value happens to be the "string" hex code representation of an ObjectId, spring data will auto-convert that to an ObjectId when saving to the database and auto-translate the ObjectId to a String when reading it back out to the bean.

Basically the spring-data-mongo does the magic for you. I doubt they changed that behavior from the 1.x days but I might be wrong.

Upvotes: 2

Related Questions