Spring:JPA将本机SQL转换为非实体pojo

时间:2017-06-08 05:50:42

标签: java spring jpa pojo

我有本机SQL,它返回对象集合,我想将结果作为对象集合(一个非实体的pojo类)

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

I am using spring jpa 1.10

2 个答案:

答案 0 :(得分:1)

无法在JPA 1中映射非实体类。

从JPA 2.1开始,您可以使用ConstructorResultSqlResultSetMapping注释结合使用,将SQL查询的SELECT子句映射到构造函数。

以下是示例

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)
                    }
          )
       }
      )

答案 1 :(得分:0)

Mapping NativeQuery results into a POJO-这是使用@JsonFormat和ObjectMapper的JPA独立解决方案,其代码示例详细介绍了已经提到的@ darshan-patel。