By WebNest Studio Engineering Team
Advanced Java Tutorial
Entity Mapping and Configuration
Mapping is the process of telling Hibernate exactly how a Java class and its fields correspond to a database table and its columns. Modern Hibernate uses JPA annotations directly on the entity class, which keeps the mapping next to the code it describes instead of in a separate XML file.
Core Mapping Annotations
A handful of annotations cover the majority of real-world mapping needs.
@Entity— marks a class as a persistent entity; it must have a no-argument constructor and a primary key field.@Table(name = "...")— maps the class to a specific table name (optional; defaults to the class name).@Id— designates the primary key field.@GeneratedValue(strategy = GenerationType.IDENTITY)— lets the database auto-generate the primary key (e.g.AUTO_INCREMENT); other strategies includeSEQUENCEandTABLE.@Column(name = "...", nullable = false, unique = true, length = 100)— customizes how a field maps to its column.@Transient— marks a field that should not be persisted at all (e.g. a computed, in-memory-only value).@Enumerated(EnumType.STRING)— stores a Java enum as readable text rather than its ordinal integer, which is safer against future reordering of enum constants.
Primary Key Generation Strategies
IDENTITY delegates key generation entirely to the database's auto-increment column — simple, but it means Hibernate cannot batch inserts efficiently, since it must ask the database for the generated id after each insert. SEQUENCE uses a database sequence object to pre-allocate ids, which allows efficient batching and is generally preferred for high-throughput inserts on databases that support sequences (PostgreSQL, Oracle). TABLE emulates a sequence using an ordinary table and is the most portable but slowest option, used mainly when a database supports neither identity columns nor sequences.
hbm2ddl.auto — Schema Generation Modes
This property controls whether Hibernate touches your schema at startup: validate only checks the schema matches the entities and fails fast if not (the safest for production); update adds missing tables/columns without dropping data (convenient in early development, risky in production); create drops and recreates the schema on every startup (useful for tests); create-drop does the same but also drops everything on shutdown. Production systems typically use validate and manage real schema changes with a migration tool like Flyway or Liquibase instead.
Example
A fully annotated entity showing common mapping options
import jakarta.persistence.*;
@Entity
@Table(name = "employee", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "emp_seq")
@SequenceGenerator(name = "emp_seq", sequenceName = "employee_seq", allocationSize = 1)
private long id;
@Column(name = "full_name", nullable = false, length = 120)
private String name;
@Column(nullable = false, unique = true)
private String email;
@Enumerated(EnumType.STRING)
private Status status;
@Transient
private int yearsOfServiceComputedAtRuntime; // never persisted
public enum Status { ACTIVE, ON_LEAVE, TERMINATED }
// getters and setters
}
Hibernate: insert into employee (full_name, email, status, id) values (?, ?, ?, ?)
Common Mistakes
- Storing enums with the default (ordinal) mapping instead of @Enumerated(EnumType.STRING) — reordering enum constants later silently corrupts existing data.
- Leaving hbm2ddl.auto=update or create enabled against a production database, risking accidental data loss.
- Forgetting @Column(nullable = false) and relying only on Java-level validation, leaving the database itself able to store invalid nulls.
- Mapping a field that should be computed at runtime without @Transient, causing Hibernate to try to persist it.
Exercise
A teammate is about to make this mistake: Storing enums with the default (ordinal) mapping instead of @Enumerated(EnumType.STRING) — reordering enum constants later silently corrupts existing data. Use Core Mapping Annotations to review the decision. Write a corrected implementation or design sketch that follows @Entity, @Table, @Id, and @GeneratedValue are the essential annotations for mapping a class to a table., then name one edge case you would check.
Show hints
- Start with Core Mapping Annotations and compare your approach with A fully annotated entity showing common mapping options. Identify the decision or behavior the lesson recommends.
- Walk through your scenario step by step. Confirm that it follows @Entity, @Table, @Id, and @GeneratedValue are the essential annotations for mapping a class to a table. and that it would catch the failure described by Storing enums with the default (ordinal) mapping instead of @Enumerated(EnumType.STRING) — reordering enum constants later silently corrupts existing data..
Quick quiz
1. Which choice best describes the recommended approach in Entity Mapping and Configuration?
- A. Storing enums with the default (ordinal) mapping instead of @Enumerated(EnumType.STRING) — reordering enum constants later silently corrupts existing data.
- B. Leaving hbm2ddl.auto=update or create enabled against a production database, risking accidental data loss.
- C. @Entity, @Table, @Id, and @GeneratedValue are the essential annotations for mapping a class to a table.
Show answer
C. This is the recommended approach: @Entity, @Table, @Id, and @GeneratedValue are the essential annotations for mapping a class to a table. Avoid: Storing enums with the default (ordinal) mapping instead of @Enumerated(EnumType.STRING) — reordering enum constants later silently corrupts existing data.
Interview questions
Why does this principle matter in Entity Mapping and Configuration: @Entity, @Table, @Id, and @GeneratedValue are the essential annotations for mapping a class to a table.
Show answer
@Entity, @Table, @Id, and @GeneratedValue are the essential annotations for mapping a class to a table. Apply this in Core Mapping Annotations; the example A fully annotated entity showing common mapping options shows one way to do it. Avoid Storing enums with the default (ordinal) mapping instead of @Enumerated(EnumType.STRING) — reordering enum constants later silently corrupts existing data. and explain how your implementation or design prevents that failure.
Key Points to Remember
- @Entity, @Table, @Id, and @GeneratedValue are the essential annotations for mapping a class to a table.
- GenerationType.IDENTITY is simple but limits insert batching; SEQUENCE allows efficient batched inserts on databases that support it.
- Always map enums with EnumType.STRING to avoid data corruption if enum ordering changes.
- Use hbm2ddl.auto=validate (or a dedicated migration tool) in production instead of letting Hibernate auto-alter the schema.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
These examples need a JDK project with their libraries on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering