JPA: When do eager fetching result in StackOverflo

2019-09-12 13:04发布

问题:

  1. Do we have some set of rules when we should abstain of using FetchType.EAGER?

  2. I have heard that some of JPA frameworks (eg. Hibernate) should resolve cyclic dependencies.

    • Do we have some advice when it comes risky to relay on frameworks?
    • Do StackOverflowError along with FetchType.EAGER is always about bug in framework(I mean if I have like 3 rows in two tables)?

回答1:

One good reason to avoid FetchType.EAGER is that you can always enable eager fetching manually in JPQL (with JOIN FETCH), but you can't enable lazy fetching if you've set FetchType.EAGER.



回答2:

EAGER:

  • Convenient, but slow

  • Use Eager when your parent class always need associate class.

LAZY:

  • More coding, but much more efficient

  • Basically lazy loading has more benefits than the eager alternative (performance, use of resources) . you should generally not configure it for eager fetching, unless you experience certain issues.

    • Sharing a domain instance accross different hibernate sessions (eg. when putting a domain class instance into the http session scope and accessing properties from it - such as a User)

    • When you're sure, you will access a certain relation property everytime (or most of the time) when an instance is fetched, it would also make sense to configure this relation for eager fetching.

eg: Relation Person and Address Here, its not necessary that when i load Person entity i need to fetch Address all the time so you can keep lazy .

Conclusion

The EAGER fetching strategy is a code smell. Most often it’s used for simplicity sake without considering the long-term performance penalties. The fetching strategy should never be the entity mapping responsibility. Each business use case has different entity load requirements and therefore the fetching strategy should be delegated to each individual query. The global fetch plan should only define LAZY associations, which are fetched on a per query basis. Combined with the always check generated queries strategy, the query based fetch plans can improve application performance and reduce maintaining costs.