Join fetch in Criteria API

This approach is the same as JOIN FETCH in JPQL; however, this time, we are using the Criteria API of Hibernate. The following is an example of how to use JOIN FETCH in the Criteria API:

CriteriaBuilder criteriaBuilder = 
getEntityManager().getCriteriaBuilder();
CriteriaQuery<?> query =
criteriaBuilder.createQuery(Account.class);
Root root = query.from(Account.class);
root.fetch("transactions", JoinType.INNER);
query.select(root);
query.where(criteriaBuilder.equal(root.get("accountId"),
accountId));

return (Account)this.getEntityManager().createQuery(query)
.getSingleResult();

This option has the same advantages and disadvantages as JPQL. Most of the time, when we write a query using the Criteria API, it is use case-specific. So, this option might not be a huge problem in those cases, and it would be a good approach to reduce the amount of queries performed. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset