Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 29

    Entity Mapping

    An Orders entity is a Jakarta Persistence class annotated with @Entity that maps to a table.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    An Orders entity is a Jakarta Persistence class annotated with @Entity that maps to a table. Keep mappings boring and explicit: table name, column names, nullability, indexes, and ID strategy.

    Use jakarta.persistence.* on Boot 3 / Java 21. Prefer @Enumerated(EnumType.STRING) for OrderStatus so reordering enum constants cannot corrupt rows. Store money as int totalCents (or long) — never double.

    Indexes belong on foreign keys and common filters (user_id, status). Mark created_at with updatable = false. Identity generation with Postgres often uses sequences or identity columns — be consistent with your Flyway scripts.

    Entities are persistence models, not API models. Controllers expose OrderView records; entities stay inside the service/repository boundary.

    Purpose of this lesson

    Map an Orders table to a Jakarta @Entity with safe enums, indexes, integer cents, and clear column constraints.

    Understanding the topic

    Entity mapping is the contract between Java and SQL.

    • @Entity / @Table: class ↔ table, including named indexes.
    • @Id / @GeneratedValue: primary key strategy aligned with DDL.
    • @Column: nullability, length, updatable flags.
    • @Enumerated(STRING): stable status storage.
    • Boundary: map to DTOs before HTTP.

    Step-by-step explanation

    1. Create Order under the persistence package with Jakarta annotations.
    2. Map total_cents, status, user_id, created_at.
    3. Add indexes for user and status matching Flyway.
    4. Persist via repository and verify columns with a SQL client.

    Informative example

    Orders entity (Jakarta persistence).

    java
    import jakarta.persistence.*;
    import java.time.Instant;
    @Entity
    @Table(name = "orders", indexes = {
    @Index(name = "ix_orders_user", columnList = "user_id"),
    @Index(name = "ix_orders_status", columnList = "status")
    })
    public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "user_id", nullable = false)
    private Long userId;
    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 16)
    private OrderStatus status;
    @Column(name = "total_cents", nullable = false)
    private int totalCents;
    @Column(name = "created_at", nullable = false, updatable = false)
    private Instant createdAt = Instant.now();
    protected Order() {} // JPA
    public Order(Long userId, OrderStatus status, int totalCents) {
    this.userId = userId;
    this.status = status;
    this.totalCents = totalCents;
    }
    // getters / domain methods...
    }

    Real-world use

    Finance reports filter TechLearningPRO orders by status and user. Without indexes declared and created in migrations, the admin dashboard scans the whole ledger during campaigns. The entity documents the intended indexes next to the Java model.

    Security implications

    Entity fields can leak if returned as JSON.

    • Never expose entities from controllers — over-posting and lazy graphs risk data leaks.
    • Avoid storing secrets or raw card data on Order entities.
    • Treat internal flags (fraud score) as non-API columns.

    Best practices

    • Align @Column names with Flyway snake_case.
    • Keep entities free of Jackson annotations when possible — map outward.
    • Provide a protected no-arg constructor for JPA; expose a clear domain constructor.

    Common mistakes

    • Using EnumType.ORDINAL for status.
    • Mapping amounts as floating point.
    • Importing javax.persistence on a Boot 3 project.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy prefer EnumType.STRING?+

    Answer

    Renaming or reordering enum constants does not silently remap existing ordinal integers in the database.
    2BeginnerQuestionWhich package do Boot 3 entities import?+

    Answer

    jakarta.persistence — javax.persistence is the legacy Java EE namespace.
    3IntermediateQuestionWhy keep entities out of REST responses?+

    Answer

    To avoid lazy-load failures, over-exposure of columns, and coupling clients to the persistence schema.

    Hands-on exercise

    Lab. Create the Order entity above and a matching Flyway V1__orders.sql. Save one order and query the table — confirm status is stored as a string and total_cents is an integer.

    Summary

    Solid entity mapping keeps Hibernate predictable. Next: relate orders to line items with OneToMany and friends.

    Ready to mark this lesson complete?Track your journey across the entire course.