简体   繁体   中英

DTO pattern with JPA hibernate

I'm following this tutorial about DTO and checking the way to convert Entity to DTO. I wonder what's the meaning of lazy relationship, if in the moment of converting it to DTO, I need to get the data in order to set it into the DTO class? I always need to get the data first, so does it matter if I set it lazy or eager?

In lazy loading child class values are loaded only when getter of child classes are explicitly called. But for eager loading, while invoking parent all its child class have value already loaded in it. Eager loading is slower and consumes more memory compared to lazy loading.

I suggest you move your point of view out of "what will my DTO need", as this clouds the judgment.

Eager vs. lazy is rather a design tradeoff between "how often will I need the relationships loaded", vs. "how much can it cost to load the relationship" ?

Take an extrême example. You have a persistent entity, say a Region . A Region has a relationships to all people ( Person entity) living in this Region . And people ( Person ) can know each other.

Let's imagine you eager fetch everything in this entity graph, and you have a requirement to load all regions for a screen (not the people, only the regions).

Loading all Region will eagerly load all Person living there. But as people know each other and this will be eagerly loaded too, then you load up the entire database into memory just to display regions.

Loading the whole database into memory usually is an unacceptable cost.

Wait. There's worse.

Say I want to edit a single Person . So I load it. This eagerly fetches the Person 's Region . Which eagerly fetches all Person instances in this region. And it also fetches all other Person s this one knows of, which in turn fetches those other Person 's Region , and recursively all the way down.

Even for a single Perosn I've loaded the whole database again.

Does that mean you should never have eager fetching ? No.

What it does mean is : you can put eager fetching when you know that data is often needed together, AND you can control the amount of data the fetching will incur, directly AND indirectly.

This is what is at stake : do not load your entire 200 million rows table for a single entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM