Hi there! How would I treat (im)mutable collection...
# spring
k
Hi there! How would I treat (im)mutable collections in my Spring Data (Mongo) entities? I have the following setup
Copy code
@Document
class Foo(
        test: Set<String>,
        val id: UUID = UUID.randomUUID()
) {

    private val _test: MutableSet<String> = test.toMutableSet()

    val test: Set<String>
        get() = _test

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as Foo
        return id == other.id
    }

    override fun hashCode(): Int = id.hashCode()
}

@Repository
interface FooRepository : ReactiveCrudRepository<Foo, UUID>
along with the following test
Copy code
@DataMongoTest
internal class MutableCollectionTest(
        @Autowired private val fooRepository: FooRepository
) {

    @Test
    fun `should save and retrieve Foo`() {
        // Given
        val foo = Foo(setOf("a", "b"))

        // When
        val result = fooRepository.save(foo)
                .then(fooRepository.findById(foo.id))

        // Then
        StepVerifier.create(result)
                .expectNext(foo)
                .verifyComplete()
    }
}
and it fails with:
No property test found on entity class ….Foo to bind constructor parameter to!
t
would
Copy code
@org.springframework.data.annotation.Transient
val test...
work?
Copy code
@Transient: By default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database
source: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-usage-annotations make sure you are not using
javax.persistence.Transient
though, that is for jpa only
actually looking at your code again, the annotation might go on
test
in the constructor, as that is the property that is tried to be persisted but fails. but I am just guessing to be honest
k
Looks like I got a solution … 1.
@Value("#root._test") test: …
in the constructor and make then 2.
private var(!) _test …
as backing property