Practice: Spring Data JPA interview drill
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
In a code review a teammate pastes a slow endpoint's SQL log and asks what went wrong. This drill gives you ShopLite's real code and logs to read the way an interviewer expects.
Predict the SQL Hibernate sends
Dirty checking is Hibernate comparing each managed entity with its snapshot at flush and sending one UPDATE for every entity that changed, so no save() call is needed.
This PATCH never calls save(). List the statements Hibernate sends before you read the log.
Example 1 · PATCH a price: three statements, and the UPDATE lists every column
Runs in: the finished shoplite-api project (end of Section 16, dev profile with SQL logging)
@Transactionalpublic ProductResponse patch(Integer id, PatchProductRequest request) { Product product = load(id); Category category = request.categoryId() == null ? null : categoryService.require(request.categoryId()); if (request.sku() != null) { checkSkuIsFree(id, request.sku()); } ProductMapper.applyPatch(request, category, product); return ProductMapper.toResponse(product); // 2: category.getName() loads the lazy category} // 3: commit -> dirty checking -> UPDATE
// $ curl -X PATCH http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price":1199.00}'org.hibernate.SQL: select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? org.hibernate.orm.jdbc.bind: binding parameter (1:INTEGER) <- [6] org.hibernate.SQL: select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? org.hibernate.orm.jdbc.bind: binding parameter (1:INTEGER) <- [4] org.hibernate.SQL: update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? org.hibernate.orm.jdbc.bind: binding parameter (1:BOOLEAN) <- [true] org.hibernate.orm.jdbc.bind: binding parameter (2:INTEGER) <- [4] org.hibernate.orm.jdbc.bind: binding parameter (3:VARCHAR) <- [boAt Airdopes 141] org.hibernate.orm.jdbc.bind: binding parameter (4:NUMERIC) <- [1199.00] org.hibernate.orm.jdbc.bind: binding parameter (5:VARCHAR) <- [ACC-AD141] org.hibernate.orm.jdbc.bind: binding parameter (6:INTEGER) <- [118] org.hibernate.orm.jdbc.bind: binding parameter (7:INTEGER) <- [6]
What this code does
- The first SELECT is
load(id). The second one comes from the mapper:categoryNameneeds the lazycategory, so Hibernate loads it by id while the transaction is still open. - No
save()is called: at commit Hibernate compares the product with its snapshot and sends one UPDATE. It lists all six columns with the new price1199.00, because Hibernate builds one UPDATE per entity unless@DynamicUpdateis used.
Three questions give you the list. What does each repository call load? Which lazy getters run while the transaction is open? Which managed entities changed?
Predict the output
How many statements?
Pick what Hibernate sends for each method.
Round 1 of 2
The product exists and the method is @Transactional.
Bug hunts: N+1, read-only writes and self-invocation
N+1 is one query for a list plus one more query per row, caused by touching a lazy link inside a loop.
Count the statements in each run: the same 20 orders cost 26, 5 or 2 statements.
Example 2 · The N+1 measured: 26, 5 and 2 statements for the same 20 orders
Runs in: the finished shoplite-api project (end of Section 16, dev profile with SQL logging)
List<Order> page = em.createQuery(""" select o from Order o where o.customer.id = :customer order by o.orderedAt desc, o.id""", Order.class) .setParameter("customer", MEENA) .setMaxResults(PAGE_SIZE) .getResultList(); // 1 statementpage.forEach(order -> order.getItems() // + 1 per order .forEach(item -> item.getProduct().getName())); // + 1 per productreturn page.stream().map(Order::total).toList();entities with lazy loading: 20 orders, 26 statements, 72 ms ids page, then one fetch join: 20 orders, 2 statements, 39 ms entities with lazy loading: 20 orders, 5 statements, 40 ms ids page, then one fetch join: 20 orders, 2 statements, 27 ms
What this code does
- Lines 1-2 ran with
default_batch_fetch_size=1(no batching): 1 + 20 item queries + 5 product queries = 26. Lines 3-4 ran with the app's setting of 16: the same loop sent 5 statements, IN-list batches instead of one query per row. - Paging the ids first and then loading those orders with
join fetch o.items i join fetch i.productneeds 2 statements whatever the page size. The endpoint itself uses an aggregate DTO query because it only needs the totals.
Fix N+1 by fetching what the loop needs in the first query (join fetch or an entity graph), by paging the ids first for collections, or by a DTO query when only totals are needed.
Two more bugs repeat in code reviews. A write method without its own @Transactional in a @Transactional(readOnly = true) class is never flushed, so the change is silently lost. A call on this to a @Transactional method skips the proxy, so the annotation does nothing: call another bean.
Find the bug
Find the JPA bug
Select the line that is wrong.
Change a product price inside a read-only service.
Round 1 of 2Design questions: orders, money and soft delete
The owning side is the side of a relationship with @JoinColumn (for ShopLite orders, OrderItem.order); only it writes the foreign key.
Placing an order touches four tables. Watch where each INSERT gets its order_id.
Example 3 · Placing an order: the lock, one INSERT per order and per item, dirty-checked stock
Runs in: the finished shoplite-api project (end of Section 16, dev profile with SQL logging)
Map<Integer, Product> locked = productService.lockForOrder( // SELECT ... FOR UPDATE request.items().stream().map(OrderItemRequest::productId).toList());for (OrderItemRequest item : items) { Product product = locked.get(item.productId()); productService.takeStock(product, item.quantity()); order.addItem(new OrderItem(product, item.quantity(), product.getPrice())); // copies today's price}Order saved = orders.save(order);
// curl -i -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"addressId":1,"items":[{"productId":9,"quantity":1},{"productId":6,"quantity":2}]}'select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? select a1_0.address_id,a1_0.customer_id,a1_0.is_default,a1_0.label,a1_0.line1,a1_0.city,a1_0.state,a1_0.pincode from addresses a1_0 where a1_0.address_id=? and a1_0.customer_id=? select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id in (?,?) order by p1_0.product_id for update of p1_0 insert into orders (customer_id,address_id,ordered_at,status) values (?,?,?,?) insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?) insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?) update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
What this code does
- Customer and address are read first (422 checks), then both products are locked in id order with
for update of p1_0. The order INSERT comes before the item INSERTs because each item needs the neworder_id. - The two
update productslines are dirty checking at flush: nobody calledsave(product).unit_priceis bound fromproduct.getPrice(), so a later price change never changes this order.
An order is an aggregate: Order owns its OrderItems with cascade and orphanRemoval, each item copies unit_price from the product at ordering time, and the total is computed, never stored. Set the owning side through the helper order.addItem(item); adding to order.getItems() alone leaves order_id empty.
Money is BigDecimal in Java and DECIMAL(10,2) in MySQL, compared with compareTo because equals also compares the scale. A product that was ordered is never deleted: the API answers 409 and the admin sets isActive to false (a soft delete, a flag instead of removing the row), so old orders stay readable and searches skip it.
Order of execution
Order the placing steps
Put the work of placing an order in the order it happens.
Mixed review across the whole section
Batch fetching is Hibernate loading lazy rows for several parents in one IN-list query instead of one query each; default_batch_fetch_size sets the list size.
One log, two features. Name the code line that caused each statement.
Example 4 · Two features in one log: a Specification as EXISTS, and an IN-list batch
Runs in: the finished shoplite-api project (end of Section 16, dev profile with SQL logging)
// CustomerSpecifications.hasAddressIn(city): GET /api/v1/customers?city=PuneSubquery<Integer> sub = query.subquery(Integer.class);Root<Address> address = sub.from(Address.class);sub.select(cb.literal(1)) .where(cb.equal(address.get("customer"), root), cb.equal(cb.lower(address.get("postalAddress").get("city")), city.strip().toLowerCase()));return cb.exists(sub);
// CategoryService.tree(): GET /api/v1/categories/tree// all categories, then category.getChildren() for each one (lazy, default_batch_fetch_size: 16)select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where exists(select 1 from addresses a1_0 where a1_0.customer_id=c1_0.customer_id and lower(a1_0.city)=?) order by c1_0.customer_id limit ?,? org.hibernate.orm.jdbc.bind: binding parameter (1:VARCHAR) <- [pune] org.hibernate.orm.jdbc.bind: binding parameter (2:INTEGER) <- [0] org.hibernate.orm.jdbc.bind: binding parameter (3:INTEGER) <- [20] select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 order by c1_0.category_id select c1_0.parent_id,c1_0.category_id,c1_0.name from categories c1_0 where c1_0.parent_id in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) order by c1_0.category_id org.hibernate.orm.jdbc.bind: binding parameter (1:INTEGER) <- [1] org.hibernate.orm.jdbc.bind: binding parameter (2:INTEGER) <- [2] org.hibernate.orm.jdbc.bind: binding parameter (3:INTEGER) <- [3] org.hibernate.orm.jdbc.bind: binding parameter (4:INTEGER) <- [4] org.hibernate.orm.jdbc.bind: binding parameter (5:INTEGER) <- [5] org.hibernate.orm.jdbc.bind: binding parameter (6:INTEGER) <- [6] org.hibernate.orm.jdbc.bind: binding parameter (7:INTEGER) <- [7] org.hibernate.orm.jdbc.bind: binding parameter (8:INTEGER) <- [null] org.hibernate.orm.jdbc.bind: ... parameters 9 to 16 are also [null]
What this code does
- The city filter is
exists(select 1 from addresses ...), so Asha with two Bengaluru addresses would still be counted once; the bound value is the lower-casedpune. The page has fewer rows than its size, so Spring Data skipped the count. - The tree loaded 7 categories, then all their children in one statement: Hibernate fills an IN list of 16 placeholders (the batch size) and pads the unused ones with
null, so MySQL can reuse the same statement shape.
A mixed review question joins two or three topics: a Specification that becomes an EXISTS subquery, a lazy collection loaded in IN-list batches, a paged query that skips its count. For each statement, ask whether it grows with the page size: if it does, it is an N+1 or a batch; if not, it is a fixed cost such as the count or the existence check.
Fix the error
Fix the paged fetch join
Pick the line that removes the warning.
Page the 20 latest orders of a customer.
Error
WARN HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory
Finish up
Mark complete & continue
Next: ShopLite: fix N+1 in order history