Question
What is the difference between FETCH and LOAD when using Entity Graphs in JPA?
Answer
In Java Persistence API (JPA), Entity Graphs are a powerful feature that allows you to define a graph of entities to be fetched at once. The two primary fetch strategies available are FETCH and LOAD, which dictate how associated entities are loaded. Understanding the difference between these two types is crucial for optimizing the performance of your data access layer.
// Example of using Entity Graph with FETCH in JPA
EntityGraph entityGraph = entityManager.createEntityGraph(YourEntity.class);
entityGraph.addAttributeNodes("relatedEntity");
Map<String, Object> properties = new HashMap<>();
properties.put("javax.persistence.fetchgraph", entityGraph);
YourEntity entity = entityManager.find(YourEntity.class, entityId, properties);
Causes
- FETCH retrieves the entities and their associations eagerly, meaning all specified related entities are pulled from the database in a single query, thereby reducing the number of SQL calls.
- LOAD, on the other hand, retrieves the primary entity first and fetches the associated entities lazily. Related entities are loaded on-demand when accessed for the first time.
Solutions
- Use FETCH if you need all related entities to be available immediately and you want to reduce the number of database round trips, which is beneficial for performance when relationships are always required.
- Choose LOAD if you want to optimize for memory usage and do not always need the associated entities, allowing for better control over loading related entities only when necessary.
Common Mistakes
Mistake: Confusing FETCH with LOAD and using the wrong option for a given situation.
Solution: Understand your data access patterns. Use FETCH when all related data is needed right away and LOAD when it can be deferred.
Mistake: Not understanding the implications on performance and memory.
Solution: Analyze your queries and observe the loading behavior to determine which method aligns best with your application's needs.
Helpers
- JPA Entity Graph
- FETCH vs LOAD JPA
- Java Persistence API
- Entity Graph Usage
- JPA Fetch Strategies