Hi there! Currently I need a little advice on kotl...
# announcements
k
Hi there! Currently I need a little advice on kotlin, mutable/readonly collections and MongoDB mappings. My current minimal setup is for example
Copy code
import org.springframework.boot.ApplicationRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.data.annotation.Transient
import org.springframework.data.mongodb.core.mapping.Field
import org.springframework.data.repository.reactive.ReactiveCrudRepository
import org.springframework.stereotype.Repository
import reactor.core.publisher.Flux
import java.util.*

class Test(
        list: List<String>,
        val id: UUID = UUID.randomUUID()
) {

    @Field("list")
    private val _mutableList: MutableList<String> = list.toMutableList()

    val list: List<String>
        @Transient get() = _mutableList
}

@Repository
interface TestRepository : ReactiveCrudRepository<Test, UUID>

@SpringBootApplication
class DemoMongoMappingApplication {

    @Bean
    fun runner(testRepository: TestRepository) = ApplicationRunner {_ ->
        Flux.just("a", "b", "c")
                .map { Test(listOf(it)) }
                .collectList()
                .flatMapMany { testRepository.saveAll(it) }
                .flatMap { testRepository.findById(it.id) }
                .subscribe { println("Found $it.id") }
    }
}

fun main(args: Array<String>) {
    runApplication<DemoMongoMappingApplication>(*args)
}
Sadly this fails during load of my entities with
org.springframework.data.mapping.MappingException: No property list found on entity class com.example.demomongomapping.Test to bind constructor parameter to!
. The problem seems to be with the backing property
_list
. Any suggestions how you solve those issues?
k
Maybe
@JvmField
can help?
k
@karelpeeters What do you mean exactly? Where should I apply it?
Copy code
class Test(
        list: List<String>,
        val id: UUID = UUID.randomUUID()
) {

    val list: List<String> = list.toMutableList()

    fun doSomethingMutable() {
        list as MutableList

        list.add("foo")
    }
}
would solve the issue as well … what do you guys think of that?
k
Okay so I'm not sure how spring works, what does it try to do exactly here?
k
@karelpeeters I'm not really sure either. It tries to bind the MongoDB Document to my class and seems to fail to do so. It has to something to do with the backing property because if I implement it using my last suggestion everything works fine 🤷‍♂️
a
It may also work if you change it to a var. Constructor injection is probably the best.
k
@aarjav Yeah, it probably would … but it shouldn't be
var
. I don't want to compromise my domain model for mongo technical details