springboot JPA 实现jpql查询时报错:org.springframework.core.convert.ConverterNotFoundException 解决方案

在接口中写入jpql语句想要查询表中的特定字段,接口中的代码如下:

    @Query("select unitName, createTime, status, serviceCount, averageEval from UnitDetail")
    List<UnitDetail> loadUnitDetailList();

使用postman测试时,存在错误信息如下:
·org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type [@org.springframework.data.jpa.repository.Query com.remotegov.pojo.UnitDetail] for value '{1, 2021-07-08 16:28:12.0, 0, 1, 1}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [@org.springframework.data.jpa.repository.Query com.remotegov.pojo.UnitDetail]

原因:
查询结果集封装到了Object[ ]中,并没有直接封装到unitDetail对象中,直接接收的话会产生转换异常。

解决方案:
方案1、将存储结果集的数组对象转换为Object[ ]类型;
方案2、由于Object[ ]类型操作不便,可以封装到实体类中,代码实现如下:
① 将字段值封装到对象中

    @Query("select new UnitDetail (unitName, createTime, status, serviceCount, averageEval) from UnitDetail")
    List<UnitDetail> loadUnitDetailList();

② 在实体类中添加字段对应的构造器

    public UnitDetail(String unitName, Date createTime, String status, String serviceCount, String averageEval) {
        this.unitName = unitName;
        this.createTime = createTime;
        this.status = status;
        this.serviceCount = serviceCount;
        this.averageEval = averageEval;
    }

运行后如下图,操作成功!
springboot JPA 实现jpql查询时报错:org.springframework.core.convert.ConverterNotFoundException 解决方案_第1张图片

你可能感兴趣的:(后端,java,spring,boot)