【问题标题】:Spring JPA -> Map a ResultSet to a non-existing entitySpring JPA -> 将 ResultSet 映射到不存在的实体
【发布时间】:2020-05-19 10:39:24
【问题描述】:

我需要将本机查询的返回映射到一个对象

  • 这是我的原生查询
@Query(value = "select collector from relation;", nativeQuery = true)
     Stream<RelationStatistics> findRelationsStatistics();
  • 这是我的对象
 public class RelationStatistics {
     private String collector;
     public RelationStatistics(String collector) {
         this.collector = collector;
     }
     public String getCollector() {
         return collector;
     }
     public void setCollector(String collector) {
         this.collector = collector;
     }
 }
  • 这是我的测试
    @Test
    public void test() {
        Stream<RelationStatistics> test = relations.findRelationsStatistics();
        test.forEach(item -> System.out.println(item));
    }

这个测试返回我:

    org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [RelationStatistics]

这是一个只有一个字符串属性的示例,但原始的原生查询是一个很大的请求,因此创建实体太难了。

我找到了SqlResultSetMapping,但我不太明白如何正确使用它

如果有人知道可以做什么0_o

【问题讨论】:

  • 为什么是原生查询,在 JPA 查询中您可以免费获得映射。尝试“从 RelationStatistcs r 中选择 r”和 native=false
  • 不是真的,我不能添加表关系,因为关系太多,这个例子可能不起作用:c
  • 因为我原来的请求比较复杂(45行)

标签: java spring hibernate jpa mapping


【解决方案1】:

我在这里找到了解决方案:JPA : How to convert a native query result set to POJO class collection

使用带有接口的投影作为具有 getCollector() 方法的对象并使用此映射

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2023-03-18
    • 2019-11-16
    • 2016-06-08
    • 2018-11-25
    • 1970-01-01
    • 2020-04-18
    相关资源
    最近更新 更多