O'Reilly logo

Hands-On High Performance with Spring 5 by Dinesh Radadiya, Prashant Goswami, Pritesh Shah, Subhash Shah, Chintan Mehta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Fetch join using JPQL

Normally, we call the findById method of DAO to fetch the outer or parent entity and then call the getter methods of associations. Doing so leads to n + 1 queries because the framework will execute additional queries for each association. Instead, we can write a JPQL query using the createQuery method of EntityManager. In this query, we can join our associated entity, which we want to fetch along with the outer entity by using JOIN FETCH. The following is an example of how to get JOIN FETCH entities:

Query query = getEntityManager().createQuery("SELECT a FROM Account AS a JOIN FETCH a.transactions WHERE a.accountId=:accountId", Account.class);query.setParameter("accountId", accountId);return (Account)query.getSingleResult(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required