Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data: when use Projection interfaces and DTO projections?

I have this situation:

  • Spring Data JPA: Work with Pageable but with a specific set of fields of the entity

It about to work with Spring Data and working with a specific set of fields of an @Entity

The two suggestions are totally valid for me:

  1. DTO projections
  2. Projection interfaces

Even more, in spring-data-examples appears both together (I know for sample purposes):

  • CustomerRepository.java

Thus:

  1. When is mandatory use one over the other and why?
  2. Exists a cost of performance one over the other?

Note in the Class-based Projections (DTOs) section says the following:

Another way of defining projections is by using value type DTOs (Data Transfer Objects) that hold properties for the fields that are supposed to be retrieved. These DTO types can be used in exactly the same way projection interfaces are used, except that no proxying happens and no nested projections can be applied.

Seems the advantages are: except that no proxying happens and no nested projections can be applied

like image 903
Manuel Jordan Avatar asked May 04 '18 13:05

Manuel Jordan


2 Answers

DTO Approach

Pro

  • Simple and straigt forward

Con

  • It will result in more code as you have to create DTO class with constructor and getters/setters (unless you utilize Project Lombok to avoid boilerplate code for DTOs).

  • No nested projections can be applied.

Projections

Pro

  • Less code as it uses only interfaces.

  • Nested projections can be applied

  • Dynamic projection allows you write one generic repository method to return different subset of the attributes in entity object based on client's needs.

Con

  • Spring generates proxy at runtime
  • Query could return the entire entity object from database to Spring layer though a trimmed version (via Projection) is returned from Spring layer to client. I wasn't sure about this specific disadvantage, hoping someone to edit this answer if necessary.

If you need nested or dynamic projection, you probably want Projection approach rather than DTO approach.

Refer to official Spring doc for details.

like image 138
Rony Avatar answered Sep 18 '22 01:09

Rony


I think that DTO was the first possible solution to work with a small set of data from the Entities. Today, many operations can also be made with projections, but you need to be careful with performance. If you see this Janssen's post Entities or DTOs – When should you use which projection? you will note that DTOs have better performance than projections for reading operations.

If you don't have the problem with performance, projections will be more graceful.

like image 43
gilbriatore Avatar answered Sep 21 '22 01:09

gilbriatore