Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Entity Mapping

Entity and Column Mapping

Map a Java class to a table with @Entity, @Table, @Id, @Column, @Transient and @Access. Learn the entity rules, column options and a runnable mapping stand-in.

An entity is a Java class whose instances Hibernate stores as rows. Mapping is the set of annotations that tells Hibernate which table, which columns and which rules apply. Good mapping is mostly small: a few annotations on a plain class, and defaults do the rest.

Real Hibernate code is read-only here; the runnable examples are plain-Java stand-ins that show the same logic.

The minimum entity

Java
import jakarta.persistence.*;

@Entity
public class Book {

    @Id
    private Long id;

    private String title;
    private int pages;

    protected Book() { }                      // required by JPA: no-argument constructor

    public Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }
    // getters and setters
}

The rules for an entity class:

  • Annotate it with @Entity and give it an @Id property.
  • It needs a no-argument constructor (public or protected) that Hibernate uses to create instances.
  • It must not be final, and persistent methods must not be final, because Hibernate creates proxy subclasses for lazy loading.
  • Records cannot be entities (they are final and immutable). Use records for projections instead, see native queries and projections.

By default the table is named after the class (Book) and every non-static, non-transient field becomes a column named after the field. Defaults can be changed with the annotations below.

@Table and @Entity names

Java
@Entity(name = "Book")                      // the name used in HQL; defaults to the class name
@Table(name = "books", schema = "library",
       uniqueConstraints = @UniqueConstraint(columnNames = {"isbn"}),
       indexes = @Index(name = "idx_book_title", columnList = "title"))
public class Book { ... }

@Table sets the table, schema, constraints and indexes. Constraints and indexes only matter when Hibernate generates the schema (schema generation); they document intent even when migrations own the real DDL.

@Column

Java
@Column(name = "book_title", nullable = false, length = 200)
private String title;

@Column(unique = true, length = 20, updatable = false)
private String isbn;

@Column(precision = 8, scale = 2)
private BigDecimal price;

@Column(columnDefinition = "text")
private String blurb;
Attribute Meaning
name Column name (default: field name, then the naming strategy)
nullable Generates NOT NULL; Hibernate also checks it before the INSERT
length Size of VARCHAR (default 255)
unique Generates a unique constraint
insertable, updatable Leave the column out of INSERT or UPDATE statements
precision, scale For decimals
columnDefinition Raw SQL type fragment (not portable)

nullable = false is validated by Hibernate before it sends SQL, so you get a clear PropertyValueException instead of a database error. Keep the Java field and the database constraint in agreement; a mismatch is a common source of confusing failures.

@Transient, @Basic and @Lob

Java
@Transient
private String displayLabel;               // never stored

@Basic(optional = false, fetch = FetchType.LAZY)
@Lob
private String fullText;                   // large text stored as CLOB

@Transient removes a field from the mapping (the Java transient keyword does the same). @Lob stores big text or binary data as CLOB/BLOB.

Field or property access

If @Id is on a field, Hibernate reads and writes fields directly (field access). If it is on a getter, it calls getters and setters (property access). Field access is the usual choice: your getters can contain logic without Hibernate triggering it. Do not mix both styles in one hierarchy unless you add @Access deliberately.

Stand-in: from class to CREATE TABLE

This program reads our own mini annotations and prints the CREATE TABLE text Hibernate would derive, including the nullable and length rules.

Java Stand-in: derive DDL from a mapped class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: the nullable check before INSERT

Hibernate validates nullable = false in memory. This stand-in shows the idea with a real in-memory H2 database behind it.

Java Stand-in: validate before INSERT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Marking an entity or its getters final, which breaks lazy proxies.
  • Forgetting the no-argument constructor.
  • Using equals/hashCode on every field; use the identifier or a natural key instead (more in identifiers).
  • Relying on columnDefinition strings that only work on one database.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is required for an entity class?

    Hibernate instantiates entities through a no-argument constructor and needs an identifier.
  2. 2. What does @Transient do on a field?

    A transient field is not persisted.
  3. 3. What is the default length of a String column?

    VARCHAR columns default to length 255 unless you set length.
  4. 4. Why should entity classes not be final?

    Proxies are generated subclasses, which a final class does not allow.

Summary

  • An entity needs @Entity, an @Id, a no-argument constructor and a non-final class.
  • @Table and @Column override table and column names, length, nullability and constraints.
  • @Transient leaves a field out; @Lob stores large data.
  • Field access (annotations on fields) is the usual style.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: Identifiers and Generation Strategies