Junior — Middle
How can Entity Graph be used in JPA to optimize queries?
sobes.tech AI
Answer from AI
Entity Graph in JPA allows specifying which related entities should be loaded together with the main entity to avoid the N+1 query problem and optimize performance.
You can create a NamedEntityGraph or a dynamic EntityGraph, where attributes for eager loading (fetch) are explicitly specified. For example:
EntityGraph<User> graph = entityManager.createEntityGraph(User.class);
graph.addAttributeNodes("address", "orders");
Map<String, Object> hints = new HashMap<>();
hints.put("javax.persistence.fetchgraph", graph);
User user = entityManager.find(User.class, userId, hints);
Thus, when loading the user, the related address and orders are fetched immediately, reducing the number of database queries.