Previous article gave us a runnable Maven project that saves and loads a Book. In this article, we will expand that same entity with an ISBN and publication date, give its columns explicit names, and inspect the resulting table. We will continue using Jakarta Persistence and an in-memory H2 database. Author and Publisher will become entities when we reach relationships in later tutorial.
Understand the mapping
An entity represents data with an identity. Its identifier connects a Java object to a database row. Basic attributes such as strings and dates become columns in that row.
Here is the mapping we will implement:
| Java element | Database element | Purpose |
|---|---|---|
Book |
books |
Catalog table |
id (Long) |
id (bigint) |
Assigned primary key |
title (String) |
title (varchar(200)) |
Required title |
isbn (String) |
isbn (varchar(13)) |
Required unique ISBN-13 |
publicationDate (LocalDate) |
publication_date (date) |
Optional date |
ISBN is a string because it is an identifier rather than a quantity. Our sample stores the 13 digits without hyphens. Column length describes storage; it does not validate an ISBN checksum or require exactly 13 characters.
1. Keep the existing project configuration
Continue in hibernate-book-catalog from previous tutorial using JDK 25 and Maven 3.9 or later. Keep its complete pom.xml, including compiler plugin 3.14.1, execution plugin 3.6.3, and main class org.kodejava.hibernate.BookCatalogApp.
All file paths below are relative to the Maven project root. Replace both Java files in full. We include the persistence configuration again so the example’s database settings are explicit.
2. Expand the Book entity
File: src/main/java/org/kodejava/hibernate/Book.java
package org.kodejava.hibernate;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDate;
@Entity
@Table(name = "books")
public class Book {
@Id
private Long id;
@Column(name = "title", nullable = false, length = 200)
private String title;
@Column(name = "isbn", nullable = false, unique = true, length = 13)
private String isbn;
@Column(name = "publication_date")
private LocalDate publicationDate;
protected Book() {
}
public Book(Long id, String title, String isbn, LocalDate publicationDate) {
this.id = id;
this.title = title;
this.isbn = isbn;
this.publicationDate = publicationDate;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getIsbn() {
return isbn;
}
public LocalDate getPublicationDate() {
return publicationDate;
}
}
@Entity makes the class part of the persistence model. @Table chooses its SQL table name. The entity name remains Book; SQL table names and entity names are separate concepts.
@Id identifies the primary key. It remains manually assigned so that we can focus on mapping. Later tutorial introduces generated identifiers.
@Column controls the column name and schema details. In our generated schema, nullable = false produces a non-null constraint, length sets string capacity, and unique = true requests a single-column unique constraint. See the official Column API.
publicationDate uses LocalDate, which Hibernate maps to SQL date; it has no time of day or time zone. No @Temporal annotation is needed. Nullability defaults to true, so this attribute can be absent. The explicit column name avoids relying on an automatic camel-case-to-underscore conversion.
Why are the annotations on fields?
The placement of @Id selects field access for this entity. Hibernate reads and writes fields directly, including private fields, so setters are unnecessary here. Keep mapping annotations on fields consistently. Property access instead places mappings on getters; do not mix the approaches accidentally.
Supported basic fields are persistent by default, even without @Column. To exclude a field, use Jakarta Persistence @Transient, for example for an in-memory UI selection flag. Adding a getter alone does not add a column when using field access. The Hibernate domain model guide explains these access strategies.
The entity is non-final and has a protected no-argument constructor. Hibernate needs to instantiate it when reading rows. Our public constructor is the convenient application-facing way to create a new book.
3. Configure H2 and schema generation
File: src/main/resources/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_2.xsd"
version="3.2">
<persistence-unit name="book-catalog" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>org.kodejava.hibernate.Book</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="jakarta.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:book_catalog"/>
<property name="jakarta.persistence.jdbc.user" value="sa"/>
<property name="jakarta.persistence.jdbc.password" value=""/>
<property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
The configuration is unchanged from previous tutorial. drop-and-create rebuilds the disposable schema at startup, so the new columns appear without a manual ALTER TABLE. It deletes existing mapped tables and data; use this setting only for our in-memory example. Mapping changes do not automatically migrate an existing production database. Later tutorial will introduce migrations.
4. Persist and reload the expanded entity
File: src/main/java/org/kodejava/hibernate/BookCatalogApp.java
package org.kodejava.hibernate;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;
import java.time.LocalDate;
public class BookCatalogApp {
public static void main(String[] args) {
try (EntityManagerFactory factory =
Persistence.createEntityManagerFactory("book-catalog")) {
saveBook(factory);
loadBook(factory);
}
}
private static void saveBook(EntityManagerFactory factory) {
try (EntityManager entityManager = factory.createEntityManager()) {
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
Book book = new Book(1L, "Effective Java", "9780134685991",
LocalDate.of(2018, 1, 6));
entityManager.persist(book);
transaction.commit();
System.out.println("Saved book: " + book.getTitle());
} catch (RuntimeException exception) {
if (transaction.isActive()) {
transaction.rollback();
}
throw exception;
}
}
}
private static void loadBook(EntityManagerFactory factory) {
try (EntityManager entityManager = factory.createEntityManager()) {
Book book = entityManager.find(Book.class, 1L);
if (book == null) {
throw new IllegalStateException("Book 1 was not found");
}
System.out.println("ID: " + book.getId());
System.out.println("Title: " + book.getTitle());
System.out.println("ISBN: " + book.getIsbn());
System.out.println("Publication date: " + book.getPublicationDate());
}
}
}
The date is sample catalog data. The write transaction commits the new row. Loading through a new entity manager then reconstructs a Book from stored values, rather than returning the object from the original persistence context. Resource handling and transaction boundaries follow previous tutorial.
5. Run and inspect the result
From the directory containing pom.xml, run:
mvn clean compile exec:java
Expected application output, interleaved with Hibernate logs:
Saved book: Effective Java
ID: 1
Title: Effective Java
ISBN: 9780134685991
Publication date: 2018-01-06
The generated table definition should be equivalent to:
create table books (
id bigint not null,
title varchar(200) not null,
isbn varchar(13) not null unique,
publication_date date,
primary key (id)
)
Column order and generated constraint names may differ. Look for the column types, the primary key, and the unique ISBN constraint rather than matching the SQL text exactly. Hibernate also prints an insert and a select with JDBC bind placeholders.
Mapping constraints and input validation
A non-null column does not reject an empty title such as "". A string length limit does not validate ISBN digits. Add application validation when collecting catalog input. The database constraints still protect stored data, including writes made outside Hibernate.
To explore the mapping, change the sample date to null and rerun: the final line becomes Publication date: null. To see the unique constraint, persist a second Book with another ID but the same ISBN inside the write transaction. The commit should fail; the exact exception and database message can vary. Restore the working sample before continuing.
On next tutorial, we will replace manually assigned IDs with generated entity identifiers while keeping this Book mapping.
Maven Dependencies
Keep these dependencies in pom.xml. Hibernate Core brings in the Jakarta Persistence API transitively. Java’s LocalDate needs no extra library. H2 is required at runtime because our Java code uses the Jakarta Persistence API rather than H2-specific classes.
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>7.4.17.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.5.252</version>
<scope>runtime</scope>
</dependency>
</dependencies>


