JpaRepository and the built-in CRUD methods
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite must save, look up and delete products and customers. Writing the same SQL and row-mapping code for every table is slow, and one slip in any copy breaks a page.
The repository hierarchy and the proxy Spring creates
JpaRepository<T, ID> is the Spring Data interface you extend to get ready-made CRUD, paging, sorting and JPA methods for one entity. T is the entity class and ID the type of its id.
ShopLite's INT keys map to Integer, so products use JpaRepository<Product, Integer>. Declare the empty interface, then ask Spring what it built from it.
Example 1 · src/main/java/com/shoplite/lab/RepositoryCheck.java: what Spring builds
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/ProductRepository.javapackage com.shoplite.product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Integer> { // no methods yet: save, findById, findAll, count, deleteById ... are inherited}
// src/main/java/com/shoplite/lab/RepositoryCheck.javapackage com.shoplite.lab;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;
import com.shoplite.product.ProductRepository;
@Component@Profile("proxy")class RepositoryCheck implements CommandLineRunner {
private final ProductRepository products;
RepositoryCheck(ProductRepository products) { this.products = products; }
@Override public void run(String... args) { Class<?> type = products.getClass(); System.out.println("Class Spring made: " + type.getName()); System.out.println("Is it a proxy? " + java.lang.reflect.Proxy.isProxyClass(type)); System.out.println("Interfaces: " + Arrays.stream(type.getInterfaces()) .map(Class::getSimpleName).limit(3).toList()); System.out.println("Products in table: " + products.count()); }}$ mvn spring-boot:run -Dspring-boot.run.profiles=proxy ... Class Spring made: jdk.proxy2.$Proxy107 Is it a proxy? true Interfaces: [ProductRepository, Repository, TransactionalProxy] DEBUG org.hibernate.SQL : select count(*) from products p1_0 Products in table: 15
What this code does
- Nobody wrote a class that implements
ProductRepository. At startup Spring Data creates a proxy: a generated object (herejdk.proxy2.$Proxy107, the number differs on your computer) that implements the interface. - When
count()is called, the proxy hands the work to Spring Data's ready-madeSimpleJpaRepository, which asks Hibernate, which sendsselect count(*) from products. - The runner only exists in the
proxyprofile, so the lab runs one small tour at a time.
The interface sits at the bottom of a small family, and each step adds methods:
Repositoryis an empty marker; extend it alone for a read-only repository that exposes only the methods you declareCrudRepositoryadds save, find, count and deleteListCrudRepositoryreturnsListinstead ofIterableJpaRepositoryaddsflush,saveAllAndFlushandgetReferenceById, plus sorting and paging
Why an interface and no class? In Section 15, JdbcClient repositories repeated the same SQL and row mapping for every table. Spring Data writes that code once: at startup it finds every interface that extends Repository and creates a proxy, a generated object that implements your interface and forwards each call to SimpleJpaRepository. The interface must sit inside the main class's package tree, or Spring never finds it.
ddl-auto=validate) with the ShopLite entities from the Entities module. Its application.properties logs every SQL statement on one short line (logging.pattern.console=%-5level %logger{36} : %msg%n) and each tour runs in its own profile.save, findById, findAll, existsById, count and deleteById
CRUD methods are the create, read, update and delete operations a repository inherits: save, saveAll, findById, findAll, existsById, count and deleteById.
A shop adds a keyboard, looks products up, changes a price and removes one. Run each call once and read the SQL it sends in the log.
Example 2 · src/main/java/com/shoplite/lab/CrudTour.java: every CRUD method and its SQL
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
package com.shoplite.lab;
import java.math.BigDecimal;import java.util.List;import java.util.Optional;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component@Profile("crud")class CrudTour implements CommandLineRunner {
private final ProductRepository products;
CrudTour(ProductRepository products) { this.products = products; }
@Override public void run(String... args) { System.out.println("--- save (new product)"); Product keyboard = new Product("ACC-KB100", "Zebronics Wireless Keyboard", 4, new BigDecimal("999.00"), 30); Product saved = products.save(keyboard); System.out.println("new id = " + saved.getId());
System.out.println("--- findById(1) and findById(99)"); Optional<Product> redmi = products.findById(1); Optional<Product> missing = products.findById(99); System.out.println(redmi.map(Product::getName).orElse("none")); System.out.println(missing.isPresent());
System.out.println("--- existsById(3), count()"); System.out.println(products.existsById(3) + ", " + products.count());
System.out.println("--- saveAll (two products)"); List<Product> fest = products.saveAll(List.of( new Product("FSH-FESTT", "College Fest T-Shirt", 6, new BigDecimal("349.00"), 200), new Product("FSH-FESTC", "College Fest Cap", 6, new BigDecimal("199.00"), 150))); System.out.println("ids = " + fest.stream().map(Product::getId).toList());
System.out.println("--- save (existing product: change the price)"); saved.setPrice(new BigDecimal("949.00")); products.save(saved);
System.out.println("--- deleteById(new id) and deleteById(99)"); products.deleteById(saved.getId()); products.deleteById(99); System.out.println("count = " + products.count());
System.out.println("--- findAll()"); System.out.println(products.findAll().size() + " products"); }}--- save (new product) DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) new id = 16 --- findById(1) and findById(99) 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 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=? Redmi Note 13 5G false --- existsById(3), count() DEBUG org.hibernate.SQL : select count(*) from products p1_0 where p1_0.product_id=? DEBUG org.hibernate.SQL : select count(*) from products p1_0 true, 16 --- saveAll (two products) DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) ids = [17, 18] --- save (existing product: change the price) 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=? --- deleteById(new id) and deleteById(99) 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 : delete from products 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 count(*) from products p1_0 count = 17 --- findAll() 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 17 products
What this code does
saveon a new object (idnull) sends an INSERT, and MySQL's AUTO_INCREMENT gives it id 16 on a fresh seed database.saveAllis justsavein a loop: two products, two INSERTs.saveon an object that already has an id first SELECTs the row, then sends an UPDATE. This is Hibernate's merge: it copies your object's fields onto a freshly loaded copy.deleteByIdalso SELECTs first, then DELETEs. For id 99 it finds nothing and quietly does nothing (Spring Data 3.0 and later; older versions threw an exception).
Each call is a small transaction of its own, and each one becomes SQL that you can read in the log. Reading that SQL is the habit that separates a JPA user from a JPA guesser. Two surprises are worth remembering: save on an entity that already has an id does a SELECT and then an UPDATE, and deleteById also loads the row before it deletes it.
What can go wrong: findAll() on a big table loads every row into memory. ShopLite's products table is small, but orders will grow every day. The Pagination module shows how to read one page at a time.
Predict the output
Which SQL does save send?
Read the call, then pick the SQL the log will show.
Round 1 of 2
The keyboard is brand new, so its id is null.
findById returns Optional<Product>, never null. Do not call get() on it: a missing id would become a NoSuchElementException and a 500.getReferenceById vs findById: a proxy without a SELECT
A reference is a lazy placeholder returned by getReferenceById(id): a Hibernate proxy, a subclass of your entity that knows only the id and loads the other fields on first use.
Linking an order to customer 4 needs only the id, not the whole customer. Compare findById with getReferenceById and see which one sends a SELECT.
Example 3 · src/main/java/com/shoplite/lab/ReferenceTour.java: a proxy without a SELECT
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;import org.springframework.transaction.support.TransactionTemplate;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;
@Component@Profile("reference")class ReferenceTour implements CommandLineRunner {
private final CustomerRepository customers; private final TransactionTemplate tx;
ReferenceTour(CustomerRepository customers, TransactionTemplate tx) { this.customers = customers; this.tx = tx; }
@Override public void run(String... args) { tx.executeWithoutResult(status -> { // one transaction around the block System.out.println("--- findById(3)"); Customer loaded = customers.findById(3).orElseThrow(); System.out.println("class: " + loaded.getClass().getSimpleName());
System.out.println("--- getReferenceById(4)"); Customer ref = customers.getReferenceById(4); System.out.println("class: " + ref.getClass().getSimpleName()); System.out.println("id: " + ref.getId()); System.out.println("email: " + ref.getEmail());
System.out.println("--- getReferenceById(99)"); Customer ghost = customers.getReferenceById(99); System.out.println("id: " + ghost.getId()); try { System.out.println("email: " + ghost.getEmail()); } catch (RuntimeException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); } });
System.out.println("--- getReferenceById(5) with no transaction"); Customer outside = customers.getReferenceById(5); try { System.out.println("email: " + outside.getEmail()); } catch (RuntimeException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); } }}--- findById(3) DEBUG org.hibernate.SQL : 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=? class: Customer --- getReferenceById(4) class: Customer$HibernateProxy id: 4 DEBUG org.hibernate.SQL : 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=? email: kabir.singh@example.com --- getReferenceById(99) id: 99 DEBUG org.hibernate.SQL : 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=? EntityNotFoundException: No row with the given identifier exists for entity [com.shoplite.customer.Customer with id '99'] --- getReferenceById(5) with no transaction LazyInitializationException: Could not initialize proxy [com.shoplite.customer.Customer#5] - no session
What this code does
findByIdruns the SELECT at once and returns a realCustomer.getReferenceByIdreturns aCustomer$HibernateProxyand sends nothing:getId()is answered from the id you passed in.- The first call to any other getter, here
getEmail(), makes Hibernate run the SELECT. For id 99 that SELECT finds no row, so you getEntityNotFoundExceptiononly then, not atgetReferenceById. - With no open transaction, the proxy has no database session to load itself from:
LazyInitializationException ... no session.TransactionTemplatesimply runs the block in one transaction; the Transactions module explains it.
findById asks "does this row exist, and what is in it?" and always runs a SELECT. getReferenceById says "I already know this id exists; I only need something to point at". That is perfect for setting a foreign key: in the Relationships module, order.setCustomer(customers.getReferenceById(customerId)) writes customer_id without loading the customer.
The costs: a wrong id is not noticed until a getter runs (EntityNotFoundException), and touching the proxy after the transaction has ended fails with LazyInitializationException. When you need the data, or need to check the row exists, use findById.
Turning Optional.empty() into a ProductNotFoundException and a 404
orElseThrow(() -> new ProductNotFoundException(id)) turns an empty Optional into an exception. The global handler then maps that exception to the contract's 404 ProblemDetail.
Asking for product 99 must answer 404, not 200 with an empty body. Start with the exception class the service will throw.
package com.shoplite.product;
import com.shoplite.common.ResourceNotFoundException;
/** No product has this id. The global handler turns it into a 404 ProblemDetail. */public class ProductNotFoundException extends ResourceNotFoundException {
public ProductNotFoundException(Integer id) { super("Product " + id + " was not found."); }}Example 4 · src/main/java/com/shoplite/product/ProductService.java: Optional to 404
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
package com.shoplite.product;
import org.springframework.stereotype.Service;
import com.shoplite.category.Category;import com.shoplite.category.CategoryRepository;
/** Product rules. Uses the repositories; returns DTOs, so entities never reach the controller. */@Servicepublic class ProductService {
private final ProductRepository products; private final CategoryRepository categories;
ProductService(ProductRepository products, CategoryRepository categories) { this.products = products; this.categories = categories; }
public ProductResponse get(Integer id) { Product product = products.findById(id) .orElseThrow(() -> new ProductNotFoundException(id)); String categoryName = categories.findById(product.getCategoryId()) .map(Category::getName) .orElse(null); return ProductResponse.from(product, categoryName); }}$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:36:06 GMT
{"detail":"Product 99 was not found.","instance":"/api/v1/products/99","status":404,"title":"Resource not found","type":"https://shoplite.example/problems/not-found"}
Server log:
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=?What this code does
findById(99)returnsOptional.empty().orElseThrow(() -> new ProductNotFoundException(id))turns "no row" into a meaningful exception, created only in the empty case.- The service does not know about HTTP. The global
@RestControllerAdvicefrom Section 15 maps everyResourceNotFoundExceptionto a 404 ProblemDetail with the contract'stype,titleandinstance(Jackson 3 writes the fields in alphabetical order). - Only one SELECT was sent: the product was not found, so the category was never looked up.
The exception extends Section 15's ResourceNotFoundException, and the one global handler turns it into the 404. Why not return null or the empty Optional to the controller? Then every controller method must remember to check it, and one forgotten check sends a 200 with an empty body or a 500. Throwing a meaningful exception in the service puts the rule in one place.
What can go wrong: catching the exception inside the service, or mapping it to 500 by accident. Write a test that asks for id 99 and expects 404.
Order of execution
From missing id to 404
Tap the steps in the order they happen.
Repositories are used by services only; controllers get DTOs
The layering rule: a controller calls a service, and a service calls a repository. Only services touch repositories, and controllers receive DTO records such as ProductResponse, never entities.
A controller that returned entities would tie the JSON to the table. Look at the product controller: it knows only the service and a response record.
Example 5 · src/main/java/com/shoplite/product/ProductController.java: DTOs only
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/ProductResponse.javapackage com.shoplite.product;
import java.math.BigDecimal;
/** The product JSON from the API contract. Controllers return this, never the entity. */public record ProductResponse(Integer id, String sku, String name, Integer categoryId, String categoryName, BigDecimal price, int stock, boolean isActive) {
static ProductResponse from(Product product, String categoryName) { return new ProductResponse(product.getId(), product.getSku(), product.getName(), product.getCategoryId(), categoryName, product.getPrice(), product.getStock(), product.isActive()); }}
// src/main/java/com/shoplite/product/ProductController.javapackage com.shoplite.product;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/products")class ProductController {
private final ProductService productService;
ProductController(ProductService productService) { this.productService = productService; }
@GetMapping("/{id}") ProductResponse get(@PathVariable Integer id) { return productService.get(id); // a DTO; the repository and the entity stay behind the service }}$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 200
Content-Type: application/json
Content-Length: 135
Date: Fri, 16 Oct 2026 05:36:06 GMT
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}
Server log:
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.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?What this code does
- The controller knows only
ProductServiceandProductResponse. It never seesProductRepositoryor theProductentity. - The JSON has exactly the contract's fields, including
categoryNameandisActive, which the entity does not have under those names. - Two SELECTs: one for the product, one for its category name. The Projections lesson gets both in one query with a join.
There are three reasons. Business rules (duplicate SKU, unknown category) live in one place, the service. The JSON shape is fixed by the API contract, not by the table, so a renamed column never breaks a client. And an entity outside a transaction can throw LazyInitializationException the moment Jackson touches a lazy field, which you will meet in the Relationships module.
In ShopLite the repository interfaces can even be package-private, so code outside com.shoplite.product cannot reach ProductRepository at all.
Next step
Check your understanding
12 quick questions