Skip to main content


Showing posts from April, 2018

JPA Tips: Avoiding the N + 1 select problem

Introduction ORM frameworks like JPA simplifies our development process by helping us to avoid lots of boilerplate code during the object <-> relational data mapping. However, they also bring some additional problems to the table, and N + 1 is one of them. In this article we will take a short look at the problem along with some ways to avoid them. The Problem As an example I will use a simplified version of an online book ordering application. In such application I might create an entity like below to represent a Purchase Order - @Entity public class PurchaseOrder { @Id private String id; private String customerId; @OneToMany(cascade = ALL, fetch = EAGER) @JoinColumn(name = "purchase_order_id") private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); } A purchase order consists of an order id, a customer id, and one or more items that are being bought. The PurchaseOrderItem entity might have the fo