What is the difference between FETCH and LOAD for Entity graph of JPA?

主宰稳场 提交于 2019-11-27 02:10:11

问题


I'm new to JPA and I'm trying to use entity graph. And I realized when I retrieve data, I need to specify which EntityGraphType I want to use.

I read JPA2.1 specification but I'm still not sure how can I use these 2 options properly...

the question is...

  • which option should I use if I don't have any specific reqirement?
  • what is the specific situation when I need to use Fetch and Load?

回答1:


I will begin by answering the second part of your question.

what is the specific situation when I need to use Fetch and Load?

There are two primary ways to load an entity in JPA, eager loading and lazy loading. In eager loading, an entity is immediately loaded at the time its parent gets loaded. In lazy loading, an entity is only loaded when an actual getter for that entity is called. High performance applications tend to be biased towards lazy loading because it isn't very nice to make the end user wait for an entire table, or even group of tables, to load when the application starts up. Now on to your second question.

You specify FETCH as your strategy by importing javax.persistence.fetchgraph in the file containing the entity. In this case, all attributes specified in your entity graph will be treated as FetchType.EAGER, and all attributes not specified will be treated as FetchType.LAZY. On the other hand, if you specify LOAD as your strategy by importing javax.persistence.loadgraph then all attributes specified in the entity graph are also FetchType.EAGER but attributes not specified use their specified type or default if the entity specified nothing.

which option should I use if I don't have any specific reqirement?

That being said, it is unlikely that you do not have a specific requirement. At the very least, you need your web application to run fast. For this reason, you should probably default to lazy loading. Using a FETCH graph is good option because it defaults to lazy loading except in the few special cases where you deem an attribute should be eagerly loaded.

Here is a link to a great blog which explains all of this in detail, along with code samples.



来源:https://stackoverflow.com/questions/31978011/what-is-the-difference-between-fetch-and-load-for-entity-graph-of-jpa

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