Home > Back-end >  How to convert list inside JPA query to DTO
How to convert list inside JPA query to DTO

Time:10-02

Need to convert list of accounts to accountDto. The question is how?

@Query("SELECT ac.account FROM Academy ac WHERE ac.id = :uuid")
fun findAcademyAccountsById(uuid: UUID, pageable: Pageable): List<AccountDto>

CodePudding user response:

Depends how Account and AccountDto look like and what kind of performance you are looking for. You can convert entity objects to DTO objects in Java code either manually or with a mapper e.g. MapStruct.

I think this is a perfect use case for Blaze-Persistence Entity Views.

I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.

A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:

@EntityView(Account.class)
public interface AccountDto {
    @IdMapping
    Long getId();
    String getName();
}

Querying is a matter of applying the entity view to a query, the simplest being just a query by id.

AccountDto a = entityViewManager.find(entityManager, AccountDto.class, id);

The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

Page<AccountDto> findAll(Pageable pageable);

The best part is, it will only fetch the state that is actually necessary!

  • Related