45

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?
Community
  • 1
  • 1
Naga
  • 10,944
  • 2
  • 21
  • 38

1 Answers1

72

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    Thank you for answering question! I could understand how I should use these options properly. I thought that if I use fetch option, I can not retrieve sub class data, but I still can do it if I call getter method but data will be retrieved from database when I call getter, not load parent class. – Naga Aug 13 '15 at 02:20
  • That link is broken. Do you have it saved so you can paste the contents here. ++1 for nice answer – joven Feb 18 '22 at 09:31