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();
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
