JPA: When do eager fetching result in StackOverflowError?

人盡茶涼 提交于 2019-12-13 06:14:41

问题


  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.



来源:https://stackoverflow.com/questions/39014872/jpa-when-do-eager-fetching-result-in-stackoverflowerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!