【问题标题】:How to define this native query return type?如何定义这个原生查询返回类型?
【发布时间】:2020-12-19 15:50:46
【问题描述】:

为了计算添加到数据库表名称 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);

CountByDay DTO 对象,应该包含在返回的 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]
    

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

【问题讨论】:

    标签: spring spring-boot jpa


    【解决方案1】:

    我建议你尝试使用构造函数表达式 JPQL:

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

    【讨论】:

      【解决方案2】:

      我得到了这个工作:

      1.重新定义CountByDay

      import java.util.Date;
      
      public interface CountByDay {
      Date getDateAdded();
      int getCnt();
      }
      

      2.更新查询

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

      这有帮助:No converter found capable of converting from type to type

      【讨论】:

        猜你喜欢
        • 2012-04-03
        • 1970-01-01
        • 2021-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        相关资源
        最近更新 更多