spring-projects / spring-data-jpa

Simplifies the development of creating a JPA-based data access layer.
https://spring.io/projects/spring-data-jpa/
Apache License 2.0
3.03k stars 1.42k forks source link

Dto projection does not work as expected with Kotlin data classes #3518

Closed stefanw25 closed 5 months ago

stefanw25 commented 5 months ago

When having a repository return a Kotlin data class, it won't be able to convert the entity to the data class dto. The functionality that I want to use is described here in the spring data JPA documentation.

Instead, a ConverterNotFoundException is raised:

Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [com.example.demo.model.Person] to type [com.example.demo.dto.PersonDto]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:294) ~[spring-core-6.1.8.jar:6.1.8]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:185) ~[spring-core-6.1.8.jar:6.1.8]
    at org.springframework.core.convert.support.CollectionToCollectionConverter.convert(CollectionToCollectionConverter.java:89) ~[spring-core-6.1.8.jar:6.1.8]
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41) ~[spring-core-6.1.8.jar:6.1.8]

I've created a minimal reproducible example here: https://github.com/stefanw25/spring-data-dto-projection-minimal

Spring Boot version: 3.3.0

mp911de commented 5 months ago

Right now, this is expected behavior as the backing implementation returns domain objects for findAll.

Projections only work with non-base-repository methods such as findAllBy() (note the added By). These methods do not shadow base repository methods.

stefanw25 commented 5 months ago

Thank you very much. Using findAllBy() works wonderfully.