Search code examples
springkotlinjpa

Embeddable entities with Spring Boot and Kotlin


I'm using Spring Boot 3.2.2 in a Kotlin project and trying to use Embedded objects in Entity classes

import org.springframework.data.repository.kotlin.CoroutineCrudRepository
import java.io.Serializable
import javax.persistence.Embeddable
import javax.persistence.Embedded
import javax.persistence.Entity
import javax.persistence.Id

@Entity
class TestEntity(
    @Id
    val id: Long,
    @Embedded
    val emb: Emb
)

@Embeddable
class Emb(
    val field: String
)

interface TestEntityRepository : CoroutineCrudRepository<TestEntity, Long>

So, kotlin JPA and spring plugins are used in my project:

    kotlin("plugin.jpa") version "1.9.21"
    id("io.spring.dependency-management") version "1.1.0"
    id("org.springframework.boot") version "3.2.2"

When I try to persist entity with the TestEntityRepository repository:

testEntityRepository.save(TestEntity(1L, Emb("asd")))

I'm getting the following exception:

3:37:20.336 [main] ERROR o.s.c.e.ApplicationListenerMethodAdapter - Unexpected error occurred in asynchronous listener
org.springframework.dao.InvalidDataAccessApiUsageException: Nested entities are not supported
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.writePropertyInternal(MappingR2dbcConverter.java:251)
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.writeProperties(MappingR2dbcConverter.java:218)
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.writeInternal(MappingR2dbcConverter.java:189)
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.write(MappingR2dbcConverter.java:181)
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.write(MappingR2dbcConverter.java:61)
    at org.springframework.data.r2dbc.core.DefaultReactiveDataAccessStrategy.getOutboundRow(DefaultReactiveDataAccessStrategy.java:177)
...

Seems that embedding should work, why it is not working in this particular case?


Solution

  • If you read the stacktrace the error becomes very clear

    org.springframework.dao.InvalidDataAccessApiUsageException: Nested entities are not supported at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.writePropertyInternal(MappingR2dbcConverter.java:251)

    If then you check the documentation it also becomes verified

    Convention-based Mapping

    ....

    Nested objects are not supported.

    The solution to your problem according to the documentation is to register your own converter according to your needs which will support nested objects