Lesson 11 / 25

JPA Entities

Classes mapped to tables.

@Entity, @Id and Hibernate

An @Entity class maps to a table; @Id marks the primary key and @GeneratedValue lets the database generate it. JPA (implemented by Hibernate) needs a no-argument constructor (it can be protected) and tracks loaded entities in a persistence context, writing changes at commit. In production, manage the schema with migrations (Flyway or Liquibase) rather than ddl-auto=create-drop, which the demo uses only for an in-memory database.

Entities, repositories, transactions

JPA maps classes to tables, Spring Data generates repositories, and transactions keep changes consistent.

Three ideas: entities, repositories, transactions.
Figure 4.1 — Entities, repositories and transactions.

The Product entity

This file is from a demo "shop" service generated by start.spring.io for Spring Boot 4.1.1 and Java 21 (Temurin 21.0.12), built with Maven 3.9.16; the project compiled and its tests passed. A minimal entity with a generated id, a protected no-args constructor for JPA, and getters.

package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.math.BigDecimal;

@Entity
public class Product {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private BigDecimal price;

    protected Product() { }                          // required by JPA

    public Product(String name, BigDecimal price) {
        this.name = name;
        this.price = price;
    }

    public Long getId() { return id; }
    public String getName() { return name; }
    public BigDecimal getPrice() { return price; }
}

Use migrations in production

Set ddl-auto to validate (or none) and evolve schemas with Flyway or Liquibase scripts reviewed like code.

Quick check: Why does a JPA entity need a no-argument constructor?

  • It is used for validation only
  • Spring forbids other constructors
  • It speeds up queries
  • The JPA provider uses it to create instances when loading data
Answer

The JPA provider uses it to create instances when loading data — It can be protected to discourage misuse.