问题
I understand that this is highly specific to the concrete application, but I'm just wondering what's the general opinion, or at least some personal experiences on the issue.
I have an aversion towards the 'open session in view' pattern, so to avoid it, I'm thinking about simply fetching everything small eagerly, and using queries in the service layer to fetch larger stuff.
Has anyone used this and regretted it? And is there maybe some elegant solution to lazy loading in the view layer that I'm not aware of?
回答1:
Lazy loading is only beneficial if you aren't going to use the data in question at all (e.g. showing only a list of customers, hereby ignoring the nested set of orders), or if it's not to be decided yet whether the user would like to view the data in question (e.g. having a list of customers in memory and the request for list of orders depends on future actions).
If you'll for sure show all the data at once, then lazy loading is not needed, it would only cost an extra query.
回答2:
Lazy loading is basically required if you have a well designed schema and entities that map extensively to other entities in the application. Here is a very basic example:
Person entity maps one to many Referrals
Referrals one to one Person twice (the Referrer, and the Referree)
Simple enough, right? Well, if you use eager loading in these two relationships, you could end up with a ton of subsequent queries for data you probably will not display in most circumstances.
For example:
Your app wants to load a record "PersonA", and this PersonA has 3 Referrals records, as he refered 3 customers: PersonB, PersonC, and PersonD.
So if you have Eager fetching on this relationship, JPA will load those 3 Person records. And lets say PersonC referred 10 customers, because he loves whatever your selling. Now JPA has to load those 10 customers too, again because of eager loading.
You can see where this is going. If this was a lazy loaded relationship, the only time this extra set of data would be loaded is when you directly do a getReferrals() call on it.
Personally I would avoid having to create additional methods to do these fetches. Its a lot of extra work to code, and now you need to somehow manage the state of the entities and whether or not you need to do extra loading.
JPA makes this easy if you use Lazy loading. Just do whatever get...() call you would normally do on the entity POJO and JPA does the rest.
来源:https://stackoverflow.com/questions/2706421/how-significant-are-jpa-lazy-loading-performance-benefits