2

I'm using JPA 2 in my project (eclipselink provider), and I have the following problem:

When I execute the following code:

em.createQuery("select t from " + entityName  + " t where t.id = ?1"
).setParameter(1, id)
.setHint(QueryHints.REFRESH, HintValues.TRUE)
.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.CascadeAllParts)
.getSingleResult();

JPA generates tons of queries to fetch all dependent objects( i.e ~90 queries to fetch an entity). It there any way to force JPA to use joins instead of independent queries?

Kerb
  • 1,138
  • 2
  • 20
  • 39

2 Answers2

4

You can use join fetching or batch fetching to optimize relationships. Also you should use LAZY on your relationships to avoid loading them when not required.

See, http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html

James
  • 17,965
  • 11
  • 91
  • 146
2

In your query you can use join and fetch to construct the query yourself.

So for example if your entity t has a

@OneToMany public List<RelatedEntity> things;

then your query can use:

select t from entityName t join fetch t.things where t.id = ?1

Read the documentation for JPQL (Java Persistence Query Language).

MattR
  • 6,908
  • 2
  • 21
  • 30