Sub topic 3
Mapping a class to a table with @Entity
This chapter assumes you know core Java (classes, annotations, generics), basic SQL tables and primary keys, and how a Spring Boot project is configured. You will learn which rules a class must follow to become an entity, how Hibernate derives table and column names, and how to control the mapping when the defaults do not fit.
What @Entity does
@Entity marks a class as persistent. Hibernate, the JPA provider that Spring Boot uses by default, scans for these classes at startup and builds a mapping model from them. Each instance of the class represents one row, and each mapped field represents one column.
An entity class must meet these requirements:
- It carries
@Entityand has exactly one identifier, marked with@Id(or@EmbeddedId). - It has a no-argument constructor that is
publicorprotected. Hibernate uses it to create instances when it reads rows. - It is not
final, and it has nofinalpersistent fields or methods that Hibernate must override. Hibernate creates subclasses (proxies) for lazy loading, andfinalprevents that. - It is a top-level class or a
staticnested class, not an interface or an enum.
The Author and Book classes in this tutorial follow these rules. Both declare protected Author() {} style constructors. The constructor stays hidden from application code, and Hibernate can still call it.
A complete example
The following entity shows the mapping annotations you will use most often. The class Publisher is new in this chapter and is separate from the Author and Book classes.
import jakarta.persistence.*;
import java.time.LocalDate;
@Entity
@Table(
name = "publishers",
uniqueConstraints = @UniqueConstraint(name = "uk_publishers_name", columnNames = "name")
)
public class Publisher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false, length = 120)
private String name;
@Column(name = "founded_on")
private LocalDate foundedOn;
private String websiteUrl;
@Transient
private boolean selectedInUi;
protected Publisher() {
}
public Publisher(String name, LocalDate foundedOn) {
this.name = name;
this.foundedOn = foundedOn;
}
public Long getId() { return id; }
public String getName() { return name; }
public LocalDate getFoundedOn() { return foundedOn; }
public String getWebsiteUrl() { return websiteUrl; }
public void setWebsiteUrl(String websiteUrl) { this.websiteUrl = websiteUrl; }
public boolean isSelectedInUi() { return selectedInUi; }
public void setSelectedInUi(boolean selectedInUi) { this.selectedInUi = selectedInUi; }
}This class maps to a table roughly like the following (the exact SQL depends on your database dialect):
create table publishers (
id bigint generated by default as identity primary key,
name varchar(120) not null,
founded_on date,
website_url varchar(255),
constraint uk_publishers_name unique (name)
);Three things are worth noting. websiteUrl has no annotation, yet it becomes the column website_url. selectedInUi does not appear in the table at all. The @GeneratedValue annotation is covered in the next chapter, so treat it as a given here.
Everything is mapped by default
JPA uses "configuration by exception". Every non-static, non-transient field of an entity is persistent, even if it has no annotation. This catches many beginners: a helper field you add for convenience becomes a column, and the next schema validation or insert fails with an unknown column error.
Exclude a field in one of two ways:
- Mark it with
@Transient(the JPA annotation). - Declare it with the Java
transientkeyword. This also excludes the field from Java serialization, which you may not want.
Static fields are never mapped.
Names: table and column defaults
If you omit @Table, the table name comes from the class name. If you omit @Column(name = ...), the column name comes from the field name. Spring Boot configures Hibernate with CamelCaseToUnderscoresNamingStrategy, which lowercases names and inserts underscores at word boundaries. The following table shows the results.
| Java element | Resulting database name |
|---|---|
| Class `Publisher` | `publisher` |
| Class `BookReview` | `book_review` |
| Field `websiteUrl` | `website_url` |
| Field `publishedYear` | `published_year` |
Plain Hibernate, without Spring Boot, would keep websiteUrl as it is. If your tables follow a different convention, set the names explicitly with @Table and @Column, or change the strategy with the property spring.jpa.hibernate.naming.physical-strategy.
Be careful with names that are reserved words in your database. An entity called User or Order maps to a table named user or order, which many databases reject. Name the table explicitly, for example @Table(name = "users").
Controlling columns with @Column
@Column takes the following attributes most often.
| Attribute | Default | Effect |
|---|---|---|
| `name` | derived from field | Column name |
| `nullable` | `true` | Adds `not null` to generated DDL when `false` |
| `length` | `255` | Size of `varchar` columns (strings only) |
| `unique` | `false` | Adds a unique constraint |
| `precision`, `scale` | `0` | Digits for `BigDecimal` columns |
| `updatable`, `insertable` | `true` | Excludes the column from `UPDATE` or `INSERT` statements |
A key point about nullable and length: they feed schema generation, and Hibernate also checks nullable = false before it sends an insert. They do not replace database constraints or Bean Validation. If you manage your schema with Flyway or Liquibase, these attributes are documentation unless you also add the matching constraint in your migration.
Use updatable = false for values that must never change after the first insert, such as a creation timestamp. Hibernate then leaves the column out of every UPDATE statement.
Supported field types
Hibernate maps these types without extra annotations:
- Primitives and their wrappers,
String, andBigDecimal. java.timetypes such asLocalDate,LocalDateTimeandInstant.UUID,byte[], andboolean.
Prefer wrapper types (Integer, not int) for columns that can be null. A primitive int cannot hold null, so reading a null column into it fails. The Book entity uses int publishedYear because the column is always filled. Enums and embedded value objects need extra mapping and are covered in a later chapter.
Field access and property access
JPA reads and writes values in one of two ways. With field access, Hibernate reads fields directly. With property access, it calls getters and setters. The placement of @Id decides which one applies: on a field means field access, on a getter means property access.
Field access is the common choice, and all examples here use it. It lets you write getters that contain logic, or leave out setters, without changing what is persisted. The earlier Publisher example would behave differently with property access, because isSelectedInUi would then be a persistent property.
Do not mix the two styles in one entity hierarchy unless you use @Access deliberately.
Letting Hibernate create the schema
Spring Boot exposes schema handling through spring.jpa.hibernate.ddl-auto.
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=trueThe accepted values are:
none: Hibernate does not touch the schema.validate: checks that tables and columns match the mapping and fails at startup if not.update: adds missing tables and columns, but never drops or alters existing ones.create: drops and recreates the schema at startup.create-drop: likecreate, and drops the schema at shutdown.
With an embedded database such as H2, Spring Boot defaults to create-drop, which is why tests work with no setup. For a real database, use validate or none and manage the schema with migrations. update looks convenient but can leave the schema in a state nobody can reproduce.
Common errors
No default constructor for entity: the class has only constructors with parameters. Add aprotectedno-argument constructor.No identifier specified for entity:@Idis missing, or you importedorg.springframework.data.annotation.Idinstead ofjakarta.persistence.Id.Unknown entityor an unknown column in SQL: the class sits outside the packages scanned from your@SpringBootApplicationclass, or a helper field needs@Transient.javax.persistenceimports do not compile with Spring Boot 3 and later. These versions use thejakarta.persistencepackage.
Exercise
You add the field private String displayName; to an entity and compute it in a getter. At startup with ddl-auto=validate, Hibernate fails with a missing column error for display_name. What is the cause, and what are two ways to fix it?
Show answer
Every non-static, non-transient field is persistent by default, so Hibernate expects a column display_name. Fix it by marking the field @Transient, or by removing the field and computing the value in a getter that has no backing field (which works with field access). Adding the column to the schema also removes the error, but only if you want to store the value.