Saturday, November 25, 2023

DTO projections via JPQL with Hibernate lazy initialization

DTO projections are very important to doing abstraction over model and data processing. Most common interests are fecthing data with a spesific partition and/or different format other than model. Also DTOs can be very usefull for partial database updates. In JPQL, query results can be transfered into DTOs with new keyword as following:
 
SELECT new org.module.submodule.ExampleDTO(b) FROM Book b
Also you can send parameters via constructor separately. But this approach provide you to control DTO flow and lazy initializations.
 
@Getter
@Setter
public class ExampleDTO {

    private String bookName;
    private Set<BookOwner> bookOwners;

    public ExampleDTO (Boob b) {
    
    	this.bookName = b.getName();
        this.bookOwners = b.getBookOwners();
        
        Hibernate.initialize(b.getBookOwners());
    }
}
In the constructor block, you can manage all initialization, property inclusions, property exclusions and customizations.