top of page
Search
Writer's pictureLeonard Anghel

Avoid Fetching Entity In DTO Via Constructor Expression (No Associations)

Updated: May 10, 2020

Motivation:

You should avoid fetching an entity in DTO via constructor expression to avoid potential N+1 issues.


Description:

Let's assume that we have two entities, Author and Book. There is no materialized association between them, but, both entities shares an attribute named, genre.

We want to use this attribute (genre) to join the tables corresponding to Author and Book, and fetch the result in a DTO. The result should contain the Author entity and only the title attribute from Book.


Well, when you are in a scenario as here, it is strongly advisable to avoid fetching the DTO (BookstoreDto) via constructor expression:

JPQL via constructor expression:

This approach cannot fetch the data in a single SELECT, and is prone to N+1! So, DON'T DO THIS!


Way better than this consists of using Spring projections as here, JPA Tuple or even Hibernate ResultTransformer. These approaches will fetch the data in a single SELECT.


Tam Ta Da Dam! :) The complete application is available on GitHub.


If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices".



358 views0 comments

Recent Posts

See All

How To Bulk Updates

Motivation: This article is useful if you need a fast way to update a significant amount of data in the database. Bulk operations...

Kommentare


bottom of page