【问题标题】:Projections with @Query don't work as expected when projecting to class投影到课堂时,使用 @Query 的投影无法按预期工作
【发布时间】:2018-06-23 06:46:29
【问题描述】:

当投影到界面时,一切似乎都按预期工作,并且正确映射了字段。当我尝试投影到一个类(使用兼容的构造函数)时,一切正常。当我使用 @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 Data 错误:Spring Data JPA / DATAJPA-1003

【问题讨论】:

    标签: java spring hibernate spring-data-jpa jpql


    【解决方案1】:

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

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

    【讨论】:

    • 我认为我们这样做是为了避免必须首先使用本机查询。你有理由需要使用它吗?你可以做这样的事情,它应该工作得很好:SELECT new com.example.domain.MyModel(lt, obj1, obj2) FROM LeftTable lt LEFT JOIN Obj1Class obj1 ON obj1.leftRef = lt AND <condition using right table> LEFT JOIN Obj2Class obj2 ON obj2.leftRef = lt AND <condition using right table> WHERE l.id = :id.
    【解决方案2】:

    您可以通过创建一个接受HashMap<?, ?> 并调用 Spring bean 映射器的构造函数来“强制”spring 投影:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2019-09-14
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多