java - 如何正确转换存储库 @Query 的结果?

标签 java spring

我正在尝试这样做:

@Query(value = "SELECT * from student, class where student.class = class.id ..(and more)", nativeQuery= true)
    List<MyObject> findByStudentId(@Param("studentId") long studentId);

这当前引发了转换器的异常,如下所示:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Integer] to type [com.project.model.MyObject]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:324) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]

所以我猜一定有一个转换来实现。

当我返回一个列表时效果很好,但我返回一个对象,其中字段结果作为数组。

我想知道进行此转换以继续使用我的查询而无需修改所有内容的最佳方法是什么?

最佳答案

在这种情况下,您必须创建一个自定义界面来从查询中提取结果。假设您的查询返回 Student_id、class_id、student_name、student_class 等。您所需要的只是创建一个如下所示的界面

  interface MyCustomObject{
        Long getStudentId();
        Long getClassId();      
        String getStudentName();
        String getStudentClass();            
    }

那么您的查询将是

@Query(value = "SELECT s.student_id, c.class_id, s.student_name, s.student_class from student s, class c where student.class = class.id ..(and more)", nativeQuery= true)
    List<MyCustomObject> findByStudentId(@Param("studentId") long studentId);

我建议为这种自定义查询指定选定的列名称。

关于java - 如何正确转换存储库 @Query 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47999114/

相关文章:

java - 如何在 Spring Boot 中更改允许的 header

java - Spring roo permissionEvaluator 抛出 NullPointerException

java - Spring Cache 抽象 JDK 可选

java - 如何使用ant在命令行中输入项目名称?

java - spring.tld标签库属性差异

java - 如何在 if 语句中保留我的值?

spring - 根据用户名和远程 IP 地址使用不同的 AuthenticationProvider

java - 执行方法未在预定时间调用quartz+spring

java - Spring MVC : autowiring a controller in another controller

java - 数据库关系建模