简体   繁体   English

Spring:JPA将原生SQL转换为非实体pojo

[英]Spring : JPA to convert native SQL to non entity pojo

I have native SQL which returns the collection of objects and i would like to get the results as collection of objects(a pojo class which is non entity) 我有本机SQL,它返回对象的集合,并且我想以对象的集合的形式获取结果(非实体的pojo类)

is it possible to get the results from native SQL as collection of non entity?

I am using spring jpa 1.10

There is no way to mapping non-entity classes in JPA 1. 在JPA 1中无法映射非实体类。

Since JPA 2.1, you can use ConstructorResult , Used in conjunction with the SqlResultSetMapping annotation to map the SELECT clause of a SQL query to a constructor. 从JPA 2.1开始,可以将ConstructorResultSqlResultSetMapping批注结合使用,以将SQL查询的SELECT子句映射到构造函数。

Here is the example 这是例子

Query q = em.createNativeQuery(
      "SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS avgOrder " +
      "FROM Customer c, Orders o " +
      "WHERE o.cid = c.id " +
      "GROUP BY c.id, c.name",
      "CustomerDetailsResult");

   @SqlResultSetMapping(
       name="CustomerDetailsResult",
       classes={
          @ConstructorResult(
               targetClass=com.acme.CustomerDetails.class,
                 columns={
                    @ColumnResult(name="id"),
                    @ColumnResult(name="name"),
                    @ColumnResult(name="orderCount"),
                    @ColumnResult(name="avgOrder", type=Double.class)
                    }
          )
       }
      )

将NativeQuery结果映射到POJO-这是使用@JsonFormat和ObjectMapper的 JPA独立解决方案,其代码示例详细说明了已经提到的@ darshan-patel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM