Hibernate / Hibernate 7 Basics Interview Questions
What are lazy and eager fetching in Hibernate 7 and how do you avoid the N+1 problem?
Lazy fetching loads associations on demand. Eager fetching loads them immediately. Wrong strategy choice leads to the N+1 query problem.
// LAZY (default for @OneToMany): @OneToMany(mappedBy="customer", fetch=FetchType.LAZY) private List<Order> orders; // N+1 PROBLEM: // 1 query: SELECT * FROM customers // N queries: SELECT * FROM orders WHERE customer_id=1 ... customer_id=N List<Customer> customers = session.createQuery("FROM Customer", Customer.class).getResultList(); for (Customer c : customers) { c.getOrders().size(); // triggers N extra queries! } // SOLUTION 1: JOIN FETCH List<Customer> customers = session .createQuery("FROM Customer c JOIN FETCH c.orders", Customer.class) .getResultList(); // 1 query with JOIN // SOLUTION 2: @BatchSize @OneToMany(mappedBy="customer") @BatchSize(size=25) // loads 25 collections in one IN query private List<Order> orders; // SOLUTION 3: EntityGraph EntityGraph<Customer> graph = session.createEntityGraph(Customer.class); graph.addAttributeNode("orders"); List<Customer> list = session.createSelectionQuery("FROM Customer", Customer.class) .applyFetchGraph(graph).getResultList();
More Related questions...