Skip to lesson

Practice: repositories and queries

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.

Before a report goes live, someone must decide which query style to use, what SQL it really sends and whether a change should go through entities or one bulk statement. These exercises train each decision on ShopLite data.

One query, three styles: derived, JPQL and native

"Accessories with fewer than 100 units, lowest stock first" can be a derived method, a JPQL query or a native query. Run all three and compare.

Example 1 · One question, three query styles

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

Java
// "Accessories with fewer than 100 units, lowest stock first"// ProductRepositoryList<Product> findByCategoryIdAndStockLessThanOrderByStockAscIdAsc(Integer categoryId, int stock);
@Query("select p from Product p where p.categoryId = :categoryId and p.stock < :stock order by p.stock, p.id")List<Product> lowStockInCategory(@Param("categoryId") Integer categoryId, @Param("stock") int stock);
@NativeQuery("select * from products where category_id = :categoryId and stock < :stock order by stock, product_id")List<Product> lowStockInCategoryNative(@Param("categoryId") Integer categoryId, @Param("stock") int stock);
// PracticeLessonTour (profile "p7")print(products.findByCategoryIdAndStockLessThanOrderByStockAscIdAsc(4, 100));print(products.lowStockInCategory(4, 100));print(products.lowStockInCategoryNative(4, 100));
Sample output
--- derived
DEBUG 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.category_id=? and p1_0.stock<? order by p1_0.stock,p1_0.product_id
  ACC-M331 stock 0
  ACC-USBC1 stock 0
  ACC-PB20K stock 60
--- JPQL
DEBUG 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.category_id=? and p1_0.stock<? order by p1_0.stock,p1_0.product_id
  ACC-M331 stock 0
  ACC-USBC1 stock 0
  ACC-PB20K stock 60
--- native
DEBUG org.hibernate.SQL : select * from products where category_id = ? and stock < ? order by stock, product_id
  ACC-M331 stock 0
  ACC-USBC1 stock 0
  ACC-PB20K stock 60

What this code does

  • The derived method and the JPQL query produce identical SQL. The native one is the same idea in your own words, with table and column names.
  • All three return entities and bind both values. The difference is in maintenance: the derived name is checked at startup, the JPQL is checked at startup and has a short name, the native query is checked by nobody until it runs.

Choosing a query style starts from the question, not the tool. A short lookup by one or two fields is a derived method. Several conditions, a join, a function, an aggregate or a DTO result is JPQL in @Query. A MySQL-only feature such as a window function, REGEXP or a tuned plan is native SQL.

All three bind parameters and can return entities or projections. What changes is safety and upkeep: derived and JPQL queries are checked against the entities at startup and survive a column rename through @Column; native queries are checked only when they run and break when a column is renamed. A useful habit: write the method, run it once, and read the SQL in the log before you move on.

Predict the SQL a repository method sends

Predicting SQL is the JPA skill interviewers test most. For each call ask: does it load before it writes, how many rows does it touch, and which columns does it select?

Example 2 · Predict the SQL: six repository calls and what they sent

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

Java
products.save(new Product("ACC-KB100", "Zebronics Wireless Keyboard", 4, new BigDecimal("999.00"), 30));products.save(saved);                      // saved already has id 16products.deleteById(99);                   // no such productcustomers.existsByEmail("ravi.kumar@example.com");products.findTop3ByActiveTrueOrderByPriceDesc();admin.deactivateCategory(2);               // @Modifying query in a @Transactional service
Sample output
DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?)
DEBUG 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=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
DEBUG 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=?
DEBUG org.hibernate.SQL : select c1_0.customer_id from customers c1_0 where c1_0.email=? limit ?
DEBUG 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.is_active=true order by p1_0.price desc limit ?
DEBUG org.hibernate.SQL : update products p1_0 set is_active=false where p1_0.category_id=?

What this code does

  • These lines come from the earlier tours in this module. Cover the output and predict each call before reading it.
  • The surprises are the second and third calls: save with an id does a SELECT first, and deleteById of a missing id does a SELECT and then nothing.

The common answers from this module: save on a new entity is one INSERT; save on an entity with an id is SELECT + UPDATE; deleteById and derived deleteBy load first and then delete one by one; existsBy selects one id with a limit; First/Top add limit; projections narrow the column list; a @Modifying query is exactly one statement.

Predict the output

Predict the SQL

Pick what the log shows for each call.

Round 1 of 3

No product has id 99.

// there is no product 99
products.deleteById(99);

Fix broken method names, JPQL and missing @Modifying

Three repository methods are broken. Work out which errors stop the app at startup and which wait until the method is called.

Example 3 · Three broken repositories and the messages they give

Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)

Java
// 1. Derived name with a wrong field (Product has "name", not "title")List<Product> findByTitle(String title);
// 2. JPQL with a column name@Query("select p from Product p where p.is_active = true and p.stock < :threshold")List<Product> findLowStockBroken(@Param("threshold") int threshold);
// 3. An UPDATE without @Modifying@Query("update Product p set p.active = false where p.categoryId = :categoryId")int deactivateCategory(@Param("categoryId") Integer categoryId);
Sample output
1. At startup:
Caused by: org.springframework.data.core.PropertyReferenceException: No property 'title' found for type 'Product'

2. At startup:
Caused by: org.hibernate.query.sqm.PathElementException: Could not resolve attribute 'is_active' of 'com.shoplite.product.Product'

3. At the first call:
org.springframework.dao.InvalidDataAccessApiUsageException: Query executed via 'getResultList()' or 'getSingleResult()' must be a 'select' query [update Product p set p.active = false where p.categoryId = :categoryId]

What this code does

  • Each broken method was run on its own; only the last Caused by line of each is shown. Two fail at startup, one only when called.
  • Fixes: findByName; p.active; add @Modifying and call it from a @Transactional service method.

Startup errors stop the app before Tomcat opens a port: a derived name with an unknown property ("No property 'title' found"), JPQL with an unknown attribute or entity ("Could not resolve attribute/root entity"), or a constructor expression that matches no constructor.

Runtime errors appear only when the method is called: a missing @Modifying ("must be a 'select' query"), a missing transaction ("No active transaction for update or delete query"), a named parameter with no argument, a streaming query without a transaction, and any typo in native SQL. That is why every custom repository method deserves one test that calls it against MySQL; the project lesson adds those tests to ShopLite.

Interview drill: projections, getReferenceById and bulk updates

Three topics come up again and again. Projections: why a record from select new ... sends less SQL than entities and avoids 1 + N lookups. getReferenceById: a lazy proxy for linking by id with no SELECT, which fails later if the id is wrong or the transaction has ended. Bulk updates: one statement, a required transaction, and stale entities unless you clear the persistence context.

Answer each with the SQL it produces. "It sends one UPDATE instead of one per row" is a stronger answer than "it is faster".

Finish up

Mark complete & continue

Next: ShopLite: product and customer repositories on Spring Data JPA