投影到 class 时,@Query 的投影无法按预期工作

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

当投影到界面时,一切似乎都按预期工作,并且字段映射正确。当我尝试投影到 class(使用兼容的构造函数)时,一切正常。当我使用 @Query 注释时,出现以下异常:

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);

查看示例项目:https://github.com/roberthunt/spring-data-query-projection

参见 Spring 数据错误:Spring Data JPA / DATAJPA-1003

由于 Spring 数据错误尚未解决,您应该能够通过在查询声明中使用构造函数表达式来解决此问题,即

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

您可以 "force" spring 投影,方法是创建一个接受 HashMap<?, ?> 并调用 Spring bean 映射器的构造函数:

public PersonSummary(HashMap<?, ?> resultMap) {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(this);
    wrapper.setPropertyValues(resultMap);
}

请注意,数据库返回的列必须与 class 的字段名称相匹配,包括正确的大小写。因此,例如,在使用 Postresql 时,您可能需要使用正确的大小写创建带引号的别名,例如:

@Query("SELECT p.firstname as \"firstName\" from person p where ....", nativeQuery = true)