首页 > 解决方案 > 如何定义这个原生查询返回类型?

问题描述

为了计算添加到数据库表名的项目数,url_store我使用带有 Spring JPA 的本机查询:

@Query(value="SELECT count(dateadded), dateadded from url_store WHERE dateadded >= ? and dateadded <= ? group by dateadded",
    nativeQuery=true)
    List<CountByDay> getAddedCountByDay(Date fromDate, Date toDate);

CountByDayDTO 对象,应包含在返回的 List 中:

import java.util.Date;

public class CountByDay {

    public CountByDay(Integer count, Date dateAdded){
        this.count = count;
        this.dateAdded = dateAdded;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    private Integer count;

    public Date getDateAdded() {
        return dateAdded;
    }

    public void setDateAdded(Date dateAdded) {
        this.dateAdded = dateAdded;
    }

    private Date dateAdded;

}

当我调用该getAddedCountByDay方法时,我收到错误:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [CountByDay]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321) ~[spring-core-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    

看来我没有CountByDay正确定义dto?如何正确定义 dto 以返回CountByDay对象列表?

标签: springspring-bootjpa

解决方案


我建议您尝试像这样使用构造函数表达式 JPQL:

SELECT new CountByDay(count(dateadded), dateadded) from url_store WHERE dateadded >= ? and dateadded <= ? group by dateadded

推荐阅读