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

1

47

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?
Premillennial answered 13/8, 2015 at 1:22 Comment(0)
R
75

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.

Romance answered 13/8, 2015 at 2:4 Comment(2)
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.Premillennial
But what is real difference? if I use entity graph it loads as in case of eager...Newmown

© 2022 - 2024 — McMap. All rights reserved.