Recommended way to ignore property WITHOUT using @Transient annotation in Spring Data MongoDB using Kotlin?

24 Views Asked by At

Consider the following classes:

@Document
@CompoundIndex(name = "foo_bar_label", def = "{ 'foo.bar.label': 1 }", unique = true)
data class FooHolder(
    val foo: FooDto,
    @Id
    val id: String = foo.id,
)

data class FooDto(
    val bar: BarDto,
    val id: String = UUID.randomUUID().toString()
)

data class BarDto(
    val label: String
) {
    // I want to ignore this field as though it were annotated with @Transient
    private lateinit var ignored: String

    init {
        ignored = if (label.length >= 1) {
            label.substring(0, 1)
        } else {
            ""
        }
    }
}

I want to have Spring Data MongoDB treat property ignored on Bar as though it were annotated with @Transient but not actually annotated, because I don't want my DTOs to have a dependency on Spring Data MongoDB (since they will be crossing service boundaries).

I had hoped, in a manner similar to the @CompoundIndex annotation, I could define a @Transient-like annotation at the top on my @Document class that would specify that field foo.bar.ignored is to be treated as @Transient when writing to & reading from the database.

What's the simplest way to support this scenario?

1

There are 1 best solutions below

0
Matthew Adams On

Write a converter to convert the type to an org.bson.Document.

import org.bson.Document
import org.springframework.core.convert.converter.Converter

class BarDtoToDocumentConverter : Converter<BarDto, Document> {
    override fun convert(source: BarDto): Document {
        val document = Document()
        document["label"] = source.label
        // You can exclude any fields you want to ignore here
        return document
    }
}

Register the converter.

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.mongodb.core.convert.MongoCustomConversions

@Configuration
class MongoConfig {
    @Bean
    fun customConversions(): MongoCustomConversions {
        return MongoCustomConversions(listOf(BarDtoToDocumentConverter()))
    }
}