Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 537
Naga Avatar asked Aug 13 '15 01:08

Naga


People also ask

What is entity graph in JPA?

JPA 2.1 has introduced the Entity Graph feature as a more sophisticated method of dealing with performance loading. It allows defining a template by grouping the related persistence fields which we want to retrieve and lets us choose the graph type at runtime.

What is the use of NamedEntityGraph?

NamedEntityGraph annotation defines a single named entity graph and is applied at the class level. Multiple @NamedEntityGraph annotations may be defined for a class by adding them within a javax. persistence. NamedEntityGraphs class-level annotation.


1 Answers

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.

like image 83
Tim Biegeleisen Avatar answered Sep 20 '22 19:09

Tim Biegeleisen