我可以在DAO布局中将结果转换为我的对象吗?

时间:2015-09-22 08:36:09

标签: java jpa dao

public class CustomRepositoryImpl implements CustomRepository {
    @PersistenceContext
    private EntityManager entityManager;

    public static final String QUERY_FIND = "SELECT.........";


    @Override
    public Collection<Object[]> find() {
        Query nativeQuery = entityManager.createNativeQuery(QUERY_FIND );
        return nativeQuery.getResultList();
    }
}

entityManager.createNativeQuery()方法返回Object[],但我想获得myObjects。我可以在这里将Object[]转换为myObjects,还是需要在另一个地方进行转换?

1 个答案:

答案 0 :(得分:0)

您可以使用ConstructorResult将返回的对象映射到实体对象

请参阅此帖JPA : How to convert a native query result set to POJO class collection

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