如何编写 JPA 查询来填充数据传输对象(不同于我的 @Entity 对象)?

How do I write a JPA query to populate a data transfer object (different than my @Entity object)?

我们正在使用 Java6、JPA 2.1 和 Hibernate 4.3。6.Final。我有以下代码可以找到我们的组织对象......

    final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Organization> criteria = builder.createQuery(Organization.class);
    final Root<Organization> root = criteria.from(Organization.class);

    final CriteriaQuery query = buildCriteriaQuery(builder, criteria, root, country, state, organizationTypes, parentOrg, zipCode);
    final TypedQuery<Organization> typedQuery = entityManager.createQuery(query);
    if (page != null && pageSize != null)
    {
        int first = (page - 1) * pageSize;
        typedQuery.setFirstResult(first);
        typedQuery.setMaxResults(pageSize);
    }   // if
    return typedQuery.getResultList();

这些组织对象是数据密集型对象。我们有一个数据传输对象 OrganizationDto,它只包含 Organization 字段的子集。有没有办法配置上面的内容来填充 OrganizationDto 对象而不是 Organization 对象?我想避免的是获取结果集,然后编写一个 for 循环来遍历所有结果集并创建所有数据传输对象。如果查询能够以某种方式立即填充这些数据传输对象,那就太好了。

在 JPA 2.1 规范中有几个所谓的构造函数表达式的示例,允许查询将任何 pojo 的构造函数用于 return 实例。构造函数必须将 select 列表作为参数。使用 JPQL 编写的规范中的示例之一:

"SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.quantity)
FROM Customer c JOIN c.orders o
WHERE o.quantity > 100"

将使用类型查询创建为:

CriteriaQuery<CustomerDetails> q =
cb.createQuery(CustomerDetails.class);
Root<Customer> c = q.from(Customer.class);
Join<Customer, Order> o = c.join(Customer_.orders);
q.where(cb.gt(o.get(Order_.quantity), 100));
q.select(cb.construct(CustomerDetails.class,
 c.get(Customer_.id),
 c.get(Customer_.status),
 o.get(Order_.quantity)));

假设存在 CustomerDetail 的构造函数以接收 ID、状态和数量字段,那么查询将 return 这些实例而不是实体。