Entities and Repositories

Entities and Repositories in Spring Boot: A research library keeps its books in the stacks -- long rows of shelves in the basement -- and keeps a card…

The Analogy: A Library Card Catalogue and the Stacks

A research library keeps its books in the stacks -- long rows of shelves in the basement -- and keeps a card catalogue at the front desk. Readers never wander the stacks themselves. Instead they fill in a request slip describing what they want, hand it to a clerk, and the clerk translates the slip into a search of the shelves and returns with the matching books. The catalogue and the clerk are the interface; the stacks are the storage. Keeping them separate is what lets the library reorganise the basement without teaching every reader a new floor plan.

Spring Data JPA is that arrangement. The stacks are your database table; each book is a row. An entity class is the description of one book's card -- which fields it has and how they map to columns. A repository is the clerk: you declare an interface, and Spring Data generates the implementation that talks to the stacks. You immediately get the standard errands for free -- save this, find the one with this id, count them, fetch a page -- without writing any shelf-walking code yourself, exactly as a reader gets "fetch me this book" without knowing the basement.

The elegant part is the request slip. A derived query method is a slip whose very wording is the search: findByCategoryName is read, word by word, as "find the books whose category name equals this," and findByPriceLessThanEqual as "whose price is at most this." The clerk parses the slip's phrasing into a shelf search, so you describe what you want in the method's name and never write the search by hand. And the slips are checked when you register them -- at application startup -- so a slip with nonsense wording is rejected the moment the library opens, not weeks later when a reader first hands it in.

Two failures come from the desk. The first is counting money by estimate. The library's accounts must be tallied in exact whole pennies; if the clerk adds up fines using a pocket calculator that rounds, the ledger drifts by a penny here and there until it no longer balances. Representing money as a floating-point double is that rounding calculator -- it cannot hold 0.10 exactly, so sums drift -- while BigDecimal counts in exact units and always balances. The second failure is the "just bring me everything" slip: a request for the entire stacks works fine when there are fifty books and buries the clerk when there are a million. An unbounded findAll on a table that grows without limit will exhaust memory in production, so any list that can grow must be fetched a page at a time.

Syntax or Core Structure

An entity maps a class to a table, and a repository interface extends JpaRepository to inherit the standard operations for free. Derived query methods turn a method name into a query: the name is parsed into a WHERE clause at startup, so a malformed name fails on boot rather than at first call.

@Entity @Table(name = "products")
public class Product {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    @Column(nullable = false, precision = 12, scale = 2)   private BigDecimal price;
    protected Product() { }   // JPA needs a no-arg constructor; keep it protected
}

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByCategoryName(String name);
    List<Product> findByPriceLessThanEqual(BigDecimal max);
    List<Product> findBySkuAndActiveTrue(String sku);
}

Reading each method name as a request slip, the clerk produces these WHERE clauses:

Output:

method                      generated where clause
----------------------------------------------------------
findByCategoryName          where category.name = ?
findByPriceLessThanEqual    where price <= ?
findBySkuAndActiveTrue      where sku = ? and active = true
----------------------------------------------------------
parsed at startup : yes

Each method name is parsed segment by segment: CategoryName becomes a nested property path category.name with an equality test, PriceLessThanEqual becomes price <= ?, and SkuAndActiveTrue splits on And into two conditions, the second a boolean literal. Because this parsing happens at startup, a typo like findByPirce fails the moment the application boots, when it is cheap to find, rather than lurking until the first call in production.


Technical Depth: Query Keywords, Money, and Paging

Derived query keywords

The query parser recognises a fixed vocabulary of keywords in a method name. A few cover most needs; the property comes first and an operator keyword follows it, with And and Or joining conditions.

Keyword in the nameMeaning in the WHERE clause
(none) after a propertyEquals: property = ?
LessThan, LessThanEqualproperty is below, or at most, the value
GreaterThan, GreaterThanEqualproperty is above, or at least, the value
ContainingA substring match (a LIKE query)
True, FalseA boolean literal, no bound parameter

Keep names readable: when a derived name would grow to something like findByCategoryNameAndPriceLessThanAndActiveTrueOrderByCreatedAtDesc, switch to an explicit @Query instead, which is far easier to read and change.

Money must be exact

A double cannot represent a value like 0.10 exactly, so sums of money drift by tiny amounts that accumulate into real accounting discrepancies. BigDecimal counts in exact units and always balances. The difference shows up the moment you test for equality.

@Column(precision = 12, scale = 2)
private BigDecimal price;   // never double for money

Output:

prices summed   : 0.10 0.20 0.30
expected total  : 0.60
double exact    : no
bigdecimal exact: yes
safe for money  : BigDecimal

Summing three prices that should total exactly 0.60, a double does not land on 0.60 -- the representation error means the sum is very slightly off, so an equality check fails. Counted as exact units, BigDecimal totals 0.60 precisely. For anything where a penny matters, BigDecimal with declared precision and scale is the only correct choice.

Paginate anything that can grow

A repository method that returns a List fetches every matching row, which is fine for a bounded set and catastrophic for a table that reaches a million rows. Returning a Page and passing a Pageable fetches one page at a time.

Page<Product> findByCategoryName(String name, Pageable pageable);
// repository.findByCategoryName("tools", PageRequest.of(0, 20, Sort.by("name")));

Output:

total rows      : 55
page size       : 20
pages           : 3
rows on page 0  : 20
rows on last    : 15

Fifty-five rows at a page size of twenty is three pages: the first two hold twenty rows each and the last holds the remaining fifteen. The application only ever loads twenty rows into memory at once, no matter how large the table grows, which is exactly what an unbounded fetch cannot promise.


Real World Example: A Catalogue Query Service

A catalogue service exposes two ways to read products: a paged search by category for the storefront, and a convenience method that returns "all products" for an internal export screen. The paged search is bounded -- it fetches one page. The convenience method calls findAll and returns every row. In a demo database of fifty-five products this works fine and nobody notices; the export screen loads instantly. This program models both queries against that small dataset.

@Service
public class CatalogueService {
    private final ProductRepository repo;
    public CatalogueService(ProductRepository repo) { this.repo = repo; }

    // bounded: one page at a time
    public Page<Product> browse(String category, Pageable pageable) {
        return repo.findByCategoryName(category, pageable);
    }
    // convenience: returns the WHOLE table -- fine at 55 rows, fatal at a million
    public List<Product> exportAll() {
        return repo.findAll();
    }
}

Output:

query                       rows returned  bounded
--------------------------------------------------
findByCategory (paged)      20             yes
findAll (convenience)       55             no
--------------------------------------------------
total rows        : 55
page size         : 20
pages (paged)     : 3
unbounded queries : 1

The paged browse returns twenty rows, one page of the three the fifty-five products span, and it will always return at most a page no matter how the catalogue grows. The convenience exportAll returns all fifty-five rows in one list. On this dataset both look equally healthy -- the export is only fifty-five rows, well within memory, and every test passes.

The trap is that exportAll scales with the table. The demo has fifty-five products; production has the whole catalogue, and the day it reaches a few hundred thousand rows, exportAll tries to load them all into a single list and exhausts the heap. The failure arrives in production, under real data volume, long after the code was written and tested, and it presents as an out-of-memory crash of the whole application rather than a slow query -- so the cause is not obvious from the symptom.

The model simplifies in ways worth stating. It counts "rows returned" as a fixed number, but the real hazard is that an unbounded query's cost is unbounded: memory, query time, and serialization all grow with the row count, and the model captures only the first. It also treats findAll as the only unbounded shape, when any List-returning derived query on an unfiltered or weakly-filtered table has the same problem. The real design flaw it points at is the asymmetry the API hides: findByCategoryName returning a Page and findAll returning a List look like sibling methods, but one has a memory ceiling and the other does not, and nothing in the type or the name warns the caller. A repository that offers an unbounded List method at all is handing every future caller a loaded gun; the safe design is to make paging the only option for any table that can grow.


Common Mistakes

  1. Storing money in a double or float. Floating-point types cannot represent decimal fractions like 0.10 exactly, so sums drift and totals fail to balance. Use BigDecimal with declared precision and scale for any monetary value.
  1. Returning an unbounded List from a query on a growing table. findAll and List-returning derived queries load every matching row into memory, which is fine in a demo and fatal in production. Return a Page and accept a Pageable for anything that can grow.
  1. Returning null instead of Optional for a lookup that may miss. A null return invites a NullPointerException layers away from the cause. Return Optional so the caller is forced to handle absence at the call site.
  1. Writing derived query names so long they are unreadable. A name with four conditions and an ordering is impossible to read and easy to get wrong. Once a derived name grows past two or three conditions, switch to an explicit @Query.
  1. Omitting the no-arg constructor, or making it public. JPA needs a no-arg constructor to instantiate rows reflectively, so its absence breaks loading. Make it protected so application code cannot build an invalid entity through it.
  1. Exposing the entity through the repository return type and then out of the API. The repository returns entities, and passing them straight to the web layer re-creates the entity-leak and lazy-loading problems from the controllers lesson. Map to a response type at the boundary.
  1. Assuming a derived query typo fails at startup for every case. Property-name typos are caught at boot, but a logically wrong-but-valid name -- querying the wrong field that happens to exist -- parses cleanly and returns wrong data silently. Test the query, do not just trust that it booted.
  1. Fetching a whole collection to count or check existence. Loading a list to call .size() or .isEmpty() pulls every row. Use count and exists derived methods, which push the work to the database and return a single value.
  1. Ignoring the page metadata and only reading the content. A Page carries the total count and page count, which clients need to render paging controls. Discarding it and returning only the content list forces clients to guess whether more pages exist.

Best Practices

  • Represent every monetary amount as BigDecimal with explicit precision and scale, and never let a double touch money.
  • Return a Page for any query over a table that can grow, so the application loads a bounded number of rows regardless of table size.
  • Return Optional from lookups that may find nothing, forcing callers to handle absence rather than risk a null-pointer far from the cause.
  • Keep derived query names short and readable, and move anything with several conditions or an ordering into an explicit @Query.
  • Give each entity a protected no-arg constructor for JPA and construct valid entities through a real constructor or factory that enforces invariants.
  • Map entities to dedicated response types at the web boundary, keeping persistence objects out of the API exactly as the controllers lesson requires.
  • Use count and exists derived methods for tallies and presence checks, letting the database do the work instead of loading rows.
  • Return and use the full Page object so clients get total counts and can render paging, rather than a bare content list.

Practice Exercises

  1. Write repository methods for: fetch a user by email (which may not exist), check whether an email is already taken, and list active users newest-first with paging. State the return type of each and why.
  1. A colleague stores prices as double and a monthly total is off by a few pennies. Explain the root cause, and show the field declaration that fixes it.
  1. Read the method name findByStatusAndPriceGreaterThanEqual and write out the WHERE clause the parser generates, identifying each property and operator.
  1. An internal report calls findAll on a table that has grown to hundreds of thousands of rows and the service now crashes with an out-of-memory error. Explain why it worked in testing, and rewrite the method to be safe.