JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
A Book class becomes a book table: every annotation and the column it produces, IDENTITY versus SEQUENCE ids, the ORDINAL enum trap that turns The Hobbit into a mystery, and LocalDate versus Instant.
What you will learn
- Map a class to a table with @Entity, @Id, @Column and @ManyToOne
- Choose between GenerationType.IDENTITY and SEQUENCE by reading the SQL
- Store enums with EnumType.STRING and see why ORDINAL breaks
- Map LocalDate and Instant and fill a timestamp with @CreationTimestamp
Before you start
- Connect Spring Boot to PostgreSQL
- Java classes, constructors and enums
Here is the whole idea in one line: a class is a table, a field is a column, and an object is a row. You describe the data once, in a Java class, and Hibernate writes both the table and the SQL.
We use a small library app with two classes, Book and Author, on PostgreSQL. The same rules map every Relay class later (tickets, customers, agents).
The class on the left, the table on the right
Book: the mapping
package org.studyeasy.library;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import java.time.Instant;
import java.time.LocalDate;
import org.hibernate.annotations.CreationTimestamp;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 200)
private String title;
@Column(nullable = false, length = 20)
private String isbn;
@Enumerated(EnumType.STRING)
private Genre genre;
private LocalDate publishedOn;
@CreationTimestamp
private Instant createdAt;
@ManyToOne
private Author author;
protected Book() {
}
public Book(String title, String isbn, Genre genre, LocalDate publishedOn, Author author) {
this.title = title;
this.isbn = isbn;
this.genre = genre;
this.publishedOn = publishedOn;
this.author = author;
}
@Override
public String toString() {
return id + " | " + title + " | " + genre + " | " + publishedOn + " | " + author.getName();
}
}
Line by line:
@Entitysays this class is a table.@Idwith@GeneratedValueis the primary key, numbered for you.@Column(nullable = false, length = 200)givesvarchar(200) not null.@Enumerated(EnumType.STRING)stores the genre by its name.@CreationTimestampfillscreatedAtwhen the book is saved.@ManyToOnemeans many books, one author, so the table gets anauthor_idcolumn pointing atauthor.- The
protectedempty constructor is the one Hibernate calls to build aBookfrom a row.
In application.yml, ddl-auto: create lets Hibernate build the tables from the entities, which is fine while you learn, and show-sql: true prints every statement. (Later in the section, Flyway takes over the tables.)
Save two books and read them back
@Component
public class LibraryRunner implements CommandLineRunner {
private final EntityManager em;
public LibraryRunner(EntityManager em) {
this.em = em;
}
@Override
@Transactional
public void run(String... args) {
long saved = em.createQuery("select count(b) from Book b", Long.class).getSingleResult();
if (saved == 0) {
Author tolkien = new Author("J. R. R. Tolkien");
Author hawking = new Author("Stephen Hawking");
em.persist(tolkien);
em.persist(hawking);
em.persist(new Book("The Hobbit", "9780547928227", Genre.FANTASY, LocalDate.of(1937, 9, 21), tolkien));
em.persist(new Book("A Brief History of Time", "9780553380163", Genre.SCIENCE, LocalDate.of(1988, 3, 1), hawking));
em.flush();
em.clear();
}
em.createQuery("select b from Book b order by b.id", Book.class)
.getResultList()
.forEach(b -> System.out.println("Read back: " + b));
}
}
Read back: 1 | The Hobbit | FANTASY | 1937-09-21 | J. R. R. Tolkien
Read back: 2 | A Brief History of Time | SCIENCE | 1988-03-01 | Stephen Hawking
When you call persist, the new Book still has id = null. Hibernate sends an insert without an id, PostgreSQL numbers the row, and the same object comes back with id = 1. Reading goes the other way: each row becomes a new Book through the empty constructor, then Hibernate fills the fields.
Now look at what PostgreSQL really built, with \d book in psql (trimmed):
published_on | date | | |
author_id | bigint | | |
created_at | timestamp(6) with time zone | | not null |
id | bigint | | not null | generated by default as identity
isbn | character varying(20) | | not null |
title | character varying(200) | | not null |
genre | character varying(255) | | |
Check constraints:
"book_genre_check" CHECK (genre::text = ANY (ARRAY['FANTASY'::character varying, 'SCIENCE'::character varying, 'HISTORY'::character varying]::text[]))
Foreign-key constraints:
"fkklnrv3weler2ftkweewlky958" FOREIGN KEY (author_id) REFERENCES author(id)
These are the types a DBA would pick. Hibernate even added a check constraint listing the three genre names.
Who makes the number? IDENTITY or SEQUENCE
With IDENTITY, the database counts, and the insert has no id in it. Switch to GenerationType.SEQUENCE and run again:
create sequence book_seq start with 1 increment by 50
...
select nextval('book_seq')
...
insert into book
(author_id, created_at, genre, isbn, published_on, title, id) values (?, ?, ?, ?, ?, ?, ?)
Now Hibernate creates a counter called book_seq, asks it for the next value, and sends the id inside the insert. Start with IDENTITY: one insert, nothing extra to set up. The other common choice is a UUID, a long random id.
Break it: the ORDINAL enum trap
Delete the @Enumerated(EnumType.STRING) line. The default is ORDINAL, so Hibernate stores the position of the constant:
id | title | genre
----+-------------------------+-------
1 | The Hobbit | 0
2 | A Brief History of Time | 1
Just numbers. Now a teammate adds a genre at the start of the enum: MYSTERY, FANTASY, SCIENCE, HISTORY. Keep the rows (ddl-auto: update) and read them back:
Read back: 1 | The Hobbit | MYSTERY | 1937-09-21 | J. R. R. Tolkien
Read back: 2 | A Brief History of Time | FANTASY | 1988-03-01 | Stephen Hawking
The Hobbit is now a mystery, and the science book is fantasy. The numbers in the table didn't change. Their meaning did. Keep EnumType.STRING on every enum.
A date, and a moment in time
The Hobbit | 1937-09-21 | 2026-10-25 23:24:32.516918+00
A Brief History of Time | 1988-03-01 | 2026-10-25 23:24:32.52214+00
LocalDate becomes date: a day on the calendar, no time. Instant becomes timestamp(6) with time zone: one exact moment, so every server agrees on it whatever its time zone. You never set createdAt; @CreationTimestamp filled it on save.
Why not plain JDBC?
The project also has plain/JdbcWay.java, which does one insert by hand: an SQL string with every column name typed out, then five setXxx calls whose numbers must match the question marks. It works (1 row inserted), but every time the class changes, you have to keep the SQL in step by hand. With an entity, the class is the only place you change.
Common mistakes
- No empty constructor. Hibernate needs one to build objects from rows. Make it
protectedso your own code uses the real one. - Leaving enums on the default.
ORDINALsilently corrupts meaning when the enum changes order. - Using
LocalDateTimefor "when it happened". It has no zone. UseInstantfor moments. - Keeping
ddl-auto: createin production. It drops and rebuilds tables. Use migrations instead.
Recap
| Annotation | Column it produces |
|---|---|
@Id @GeneratedValue(IDENTITY) | bigint generated by default as identity |
@Column(nullable = false, length = 200) | varchar(200) not null |
@Enumerated(EnumType.STRING) | varchar holding FANTASY |
LocalDate / Instant | date / timestamp(6) with time zone |
@ManyToOne | author_id bigint with a foreign key |
Try it yourself
Add a pages field of type int to Book, run with ddl-auto: create, and check \d book. Is the new column nullable? Why does a primitive int behave differently from Integer?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
