Projections with @Query don't work as expected when projecting to class

When projecting to an interface everything seems to work as expected with the fields are being mapped correctly. When I attempt to project into a class (with a compatible constructor) it all seems work fine unless I use an @Query annotation where it fails with this exception:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.HashMap<?, ?>] to type [com.example.PersonSummary]

// works
PersonSummary findPersonSummaryById(long id);

// doesn't work
@Query("SELECT name AS name, age AS age FROM Person WHERE id = :id")
PersonSummary findPersonSummaryByIdQuery(@Param("id") long id);

See example project: https://github.com/roberthunt/spring-data-query-projection

See Spring Data Bug: Spring Data JPA / DATAJPA-1003

1 answer

  • answered 2018-01-14 12:08 Je Suis Alrick

    Since the Spring Data bug has not been resolved, you should be able to work around this by using a constructor expression in the query declaration, i.e.

    @Query("select new com.example.PersonSummary(name, age) …")