What is the relationship between DTO and lazy-loading in Hibernate

sajjad jafari :

I know what is DTO: An object that carries data between processes in order to reduce the number of method calls. and I know what is lazy-loading in hibernate.

I read this sentences in "Full Stack Development with JHipster" book : JHipster uses DTO (Data Transfer Object) and VM (View Model) on the server side. DTOs are for transferring data from the service layer to and from the resource layer. They break the Hibernate transactions and avoids further lazy loading from being triggered by the resource layer.

I don't understand the relationship between DTO and lazy loading.

Vlad Mihalcea :

Lazy loading is for entities, not DTOs.

A JPA entity can be represented as a POJO or a Proxy.

As I explained in this article, using EntityManager.find gives you a POJO:

Post post = entityManager.find(Post.class, postId);

While the EtityManager.getReference method gives you a Proxy:

Post post = entityManager.getReference(Post.class, postId);

The POJO has its basic properties initialized because a SELECT statement was executed to fetch the entity. The Proxy does not hit the database upon creation. Only the id is set based on the provided entity identifier. Only you access the Proxy properties, a SELECT statement will be executed.

Proxies are also used for collections (e.g. @OneToMany or @ManyToMany) which are using the FetchType.LAZY strategy by default. Once you access the LAZY collection, a SELECT statement will be executed to fetch the associated collection.

Now, a DTO is based on a projection, hence a SELECT statement is executed prior to populating the DTO. For this purpose, you can say that the DTO is eagerly loaded every time.

DTOs are much more efficient than entities for read-only projections because you load just the table columns that you explicitly requested. For more details about the best way to use DTOs with JPA and Hibernate, check out this article.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113927&siteId=1