【问题标题】:Spring JPA Projection - Queried Data from jpa repositorySpring JPA Projection - 来自 jpa 存储库的查询数据
【发布时间】:2019-07-22 20:21:11
【问题描述】:

我不知道这是否可能,但我正在尝试将从 JPA 存储库查询的数据投影到 DTO 中

我有以下疑问:

@Query(value =
        "SELECT crop.id, count(*) as total " +
        "FROM xxx.crop_sub_plot " +
        "join crop on crop.id = crop_sub_plot.crop_id " +
        "join sub_plot on sub_plot.id = crop_sub_plot.sub_plot_id " +
        "where sub_plot.enabled = true " +
        "group by crop_id " +
        "order by total DESC;", nativeQuery = true)
List<CropUsedView> findCropsInUseOrderByDesc();

和 DTO:

public class CropUsedView implements Serializable{

private BigInteger id;
private BigInteger total;

public CropUsedView() {
}

public CropUsedView(BigInteger id, BigInteger total) {
    this.id = id;
    this.total = total;
}

//getters && setters

我收到了错误:

没有找到能够从 [java.math.BigInteger] 类型转换为 [net.xxx.crop.CropUsedView] 类型的转换器

我真的不知道这是否可能,有什么建议吗?

编辑:这是我在 MySql 上运行查询时返回数据的方式,也是我希望转换为 DTO 的方式:

【问题讨论】:

  • 尝试使用Long而不是BigInteger
  • 你返回两个值,crop.id 和一个count,并告诉 Spring 这是一个CropUsedView 的列表。也许您的意思是只返回一个对象?
  • @Cepr0 我试过了,但是不行
  • @BrunoM24 是什么错误?
  • @BrunoM24 尝试interface base projection 而不是基于类的。并将别名添加到corp.id (crop.id as id)...

标签: java spring hibernate jpa spring-data-jpa


【解决方案1】:

您的查询返回两个值:id 和计数(两者都可以映射到 longBigDecimal)。但是 Hibernate,因为它没有直接映射到一个对象,只是返回 BigDecimal[]

要解决这个问题,您应该使用自定义映射器:UserType (https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/usertype/UserType.html)。这允许您通过手动解析将任何响应映射到对象中。

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 2021-04-16
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2015-10-13
    • 1970-01-01
    • 2015-03-28
    相关资源
    最近更新 更多