Entity mapping and identity
What you will learn
Map domain objects to rows while keeping identity and relationship ownership explicit.
- Distinguish JPA, Hibernate and Spring Data.
- Explain generated identity and owning sides.
- Maintain both ends of a relationship.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. JPA examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Identity before persistence
public class Main { record Item(Long id, String sku) {} public static void main(String[] args) {var a = new Item(null,"A1"); var b = new Item(null,"B2");System.out.println(a.id() == b.id());System.out.println(a == b); }}Expected output:
truefalseBoth IDs are null; the distinct instances must not be identified as the same row. This is a Java model, not an ORM session.
Three layers
Jakarta Persistence specifies mappings and lifecycle contracts; Hibernate implements them and generates SQL; Spring Data creates repository implementations. @Entity marks a persistent class, @Id identifies its key and @GeneratedValue requests provider/database-generated values. The lab uses a protected no-argument constructor, non-final classes and field access, because @Id is on the field. Identity values may be absent before insertion. Do not equate two new objects simply because both IDs are null. Avoid mutable fields in hash keys; the lab intentionally keeps Java object identity rather than pretending its equality works across contexts.
Relationship ownership
The product holds the category foreign key, so its @ManyToOne is the owning side. The category collection uses mappedBy="category" and is inverse. Update both sides in memory; changing only the inverse collection does not establish a foreign key. No cascade is configured: persist both explicitly. Cascade propagates operations, not database constraints; orphanRemoval is for privately owned children and can delete rows when relationships are severed. Do not default to CascadeType.ALL or delete a shared category. Database NOT NULL, foreign key and unique constraints are independent of annotation metadata. The companion lab uses manually applied SQL and ddl-auto=validate, not production schema auto-update.
Maintain both sides
public class Main { record Item(String sku, Category category) {} static class Category { final java.util.List<Item> items = new java.util.ArrayList<>(); Item add(String sku) { var item = new Item(sku,this); items.add(item); return item; } } public static void main(String[] args) {var category = new Category(); var item = category.add("A1");System.out.println(item.category() == category);System.out.println(category.items.size()); }}Expected output:
true1The relationship helper sets the child reference and inserts it in the parent collection; no database operation happens.
Inverse category mapping
Source-reviewed, NOT RUN. File lab-fixtures/jpa-v40/src/main/java/example/catalog/Category.java; use the companion lab README.
package example.catalog;import jakarta.persistence.*;import java.util.*;@Entity@Table(name="category")public class Category { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column(nullable=false, unique=true, length=80) private String name; @OneToMany(mappedBy="category") private List<Product> products = new ArrayList<>(); protected Category() {} public Category(String name) { this.name = Objects.requireNonNull(name); } public Long getId() { return id; } public String getName() { return name; } public List<Product> getProducts() { return List.copyOf(products); } public Product add(String sku, int stock) { Product p = new Product(sku, stock, this); products.add(p); return p; }}Predicted behavior: Category has an inverse list and generated ID.
No automatic persist cascade.
Owning product mapping
Source-reviewed, NOT RUN. File lab-fixtures/jpa-v40/src/main/java/example/catalog/Product.java; use the companion lab README.
package example.catalog;import jakarta.persistence.*;import java.util.Objects;@Entity@Table(name="product")public class Product { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column(nullable=false, unique=true, length=12) private String sku; @Column(nullable=false) private int stock; @Version @Column(nullable=false) private long version; @ManyToOne(fetch=FetchType.LAZY, optional=false) @JoinColumn(name="category_id", nullable=false) private Category category; protected Product() {} Product(String sku, int stock, Category category) { if (sku == null || !sku.matches("[A-Z0-9]{1,12}") || stock < 0) throw new IllegalArgumentException("Invalid product"); this.sku = sku; this.stock = stock; this.category = Objects.requireNonNull(category); } public Long getId() { return id; } public String getSku() { return sku; } public int getStock() { return stock; } public long getVersion() { return version; } public Category getCategory() { return category; } public void reserve(int amount) { if (amount <= 0 || amount > stock) throw new IllegalArgumentException("Invalid reservation"); stock -= amount; }}Predicted behavior: Product owns category_id and carries a version.
The version is provider managed; never set it from client input.
Common mistakes
Do not use the generated ID before it exists, rely on mutable hash keys, or change only mappedBy. Do not confuse nullable=false with actual database enforcement.
Practice
Create two items with absent IDs and show that the two references are distinct; then compare their SKU values.
Expected output:
falsefalseCompare with the manual review criteria.
Official reading: Spec · Dependencies. ORM execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Entity mapping and identity — knowledge check
JPA mapping and persistence reasoning.
Which layer specifies portable entity mappings?
Which field owns category_id?
What does mappedBy point to?
What happens without persist cascade?
Why avoid equals based only on nullable IDs?