【问题标题】:org.springframework.core.convert.ConversionFailedException: Failed to convert from type [closed]org.springframework.core.convert.ConversionFailedException:无法从类型转换[关闭]
【发布时间】:2020-12-25 01:21:54
【问题描述】:

我正在尝试从 StudentRepository 中的表中获取数据:

 @Query("SELECT S.studentId, S.studentName, S.studentSurname, S.studentAge, S.entryYear," +
        "S.graduateYear, S.facultyName, G.groupName FROM Student S LEFT JOIN Group G ON G.groupId=G.groupId ORDER BY S.studentId")
    List<StudentDTO> getAllStudentDtos();

当我启动程序并尝试从控制器获取这些数据时:

  @GetMapping("students")
public String showStudents(Model model) {
    List<StudentDTO> students = studentService.getAllStudentDtos();
    model.addAttribute("students", students);
    return "studentViews/studentsPage";
} 

我得到了这个错误。

这里所有的例外:

org.springframework.core.convert.ConversionFailedException: Failed to convert from type
[java.lang.Object[]] to type [@org.springframework.data.jpa.repository.Query
com.foxminded.university.dto.StudentDTO] for value '{1, Alexandr, Platonchik, 37, 1999, 2004, journalism, BIKS}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Integer] to type [@org.springframework.data.jpa.repository.Query com.foxminded.university.dto.StudentDTO]

【问题讨论】:

  • 您使用的是原生查询,但未设置为 native = true

标签: java sql spring hql


【解决方案1】:

发生此错误是因为您在存储库中的方法 getAllStudentDtos 返回了 Student 列表,而不是您想象的 List&lt;StudentDTO&gt;。 Spring 存储库绑定到@Entity,在您的情况下为Student,因此当您使用该方法返回为List&lt;Student&gt; 时会出现问题。

您的问题有两种可能的解决方案。第一个是在 StudentDTO 类中声明一个构造函数,其中包含查询所需的确切字段参数,并在 getAllStudentDtos 中使用它。

例如:

public StudentDTO(Long studentId, String studentName) {
    this.studentId = studentId;
    this.studentName = studentName;
}

...

@Query("SELECT new StudentDTO(S.studentId, S.studentName) FROM Student S LEFT JOIN Group G ON G.groupId=G.groupId ORDER BY S.studentId")
List<StudentDTO> getAllStudentDtos();

请注意,我在示例中只使用了两个字段。

或者您可以在StudentDTO 中实现一个方法,将Student 实体转换为StudentDTO,然后使用您的方法映射列表。

例如:

List<StudentDTO> students = studentService.getAllStudentDtos().stream().map(student -> StudentDTO.toDto(student)).collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多