1

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

4

1 回答 1

3

在 JPA 2.1 规范中有几个所谓的构造函数表达式的例子,它们允许查询使用任何 pojo 的构造函数来返回实例。构造函数必须将选择列表作为参数。使用 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、状态和数量字段,则查询将返回这些实例而不是实体。

于 2015-08-28T00:52:35.300 回答