I have a data model with Customers, which each have n Portfolios, which in turn have n Investments, both mapped as @ManyToMany
and lazily fetched.
I also have a DTO with just the following fields:
Is it possible to write a single JPQL query that creates the DTOs using a constructor expression? Especially, how would you get a list of portfolio names in the DTO constructor?
Is it inefficient if I instead query for Customer models with portfolios and construct the DTOs myself?
You'll have to do it by yourself, and it will probably even be slightly more efficient than using a constructor in JPQL, since reflection won't be necessary:
select c.name, p.name from Customer c left join c.portfolios
Then loop over the results, and construct your results. For example:
Map<String, Result> results = new HashMap<String, Result>();
for (Object[] row : rows) {
String customerName = (String) row[0];
Result r = results.get(customerName);
if (r == null) {
result.put(customerName, new Result(customerName));
}
r.addPortfolio((String) row[1]);
}
Collection<Result> namesAndPortfolios = results.values();