简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM