简体   繁体   中英

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)

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.

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.

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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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