0

How to fetch lazy attributes in collection of entities, by not doing N calls to database. Example:

transactions = getTransactionsBySomeCriteriaApiQuery(..); // n transactions
// this make 3*n calls to DB, I want to do only a few calls
transactions.forEach(res -> {
  res.getLazyCollection1().size();
  res.getLazyCollection2().size();
  res.getLazyCollection3().size();
});
return transactions;

Assume n is big number. I would like to know if it is possible to fetch that lazy data by not making huge amount of calls to DB. I am using JPA (eclipselink), relational database.

EDIT: Indeed it is N+1 selects problem, and i would like to know how it can be resolved in eclipselink. Note that I do not want to change entity mappings from lazy to eager, because it is needed in other places. I have tried to use fetch joins (fetch on criteriaAPI), but this not working when used more than one.

Marek F
  • 505
  • 6
  • 9
  • Possible duplicate of [What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?](https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping) – crizzis Oct 07 '19 at 19:38
  • show what you've tried, but JPA has issues allowing nesting fetch joins. See http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html from https://stackoverflow.com/a/4680802/496099 . – Chris Oct 11 '19 at 14:28
  • My teammate managed to resolve this by using @NamedEntityGraph and QueryHints.JPA_LOAD_GRAPH, when I'll have time I will write the answer – Marek F Nov 22 '19 at 14:48

1 Answers1

0

Use FETCH JOIN to retrieve the actually required data in initial query.

nayakam
  • 4,149
  • 7
  • 42
  • 62
  • I have tried, and it seems to not work. I was doing few fetch joins in criteria API, each for each lazy relationship. It seems to working when used only for one lazy relationship – Marek F Oct 11 '19 at 12:01
  • ```From from = ... from.fetch("lazyCollection1"); from.fetch("lazyCollection2"); from.fetch("lazyCollection3");``` – Marek F Nov 22 '19 at 14:52