Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 119 ยท JPA and Hibernate

Entities and Hibernate Setup

Set up Hibernate with persistence.xml, then map JPA entities with @Entity, @Id, @GeneratedValue, @Table and @Column, choose ID strategies and avoid common mapping mistakes.

The previous lesson explained what an ORM does. Now it's time to set one up. Getting Hibernate running takes three things: the right dependencies, a configuration that tells it which database to use and which classes to manage, and entity classes whose annotations describe the mapping from fields to columns. Each part has defaults that are convenient, and a few that cause real damage in production if you don't understand them.

This lesson walks through a complete setup with Maven, persistence.xml and the newer programmatic configuration, then maps entities with @Entity, @Id, @GeneratedValue, @Table and @Column in detail. You'll also learn the rules an entity class must follow, how the persistence context treats your objects, and how to see the SQL Hibernate generates. Hibernate isn't available in this sandbox, so its code is read-only; the runnable programs reproduce the behavior that matters (annotation-driven mapping, ID generation, enum storage, entity equality) with plain Java and H2.

Dependencies

With Maven, one dependency brings Hibernate ORM and the Jakarta Persistence API with it; add the JDBC driver for your database next to it:

XML
<dependencies>
    <!-- Hibernate ORM 7 implements Jakarta Persistence 3.2 (pulls in jakarta.persistence-api) -->
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>7.4.13.Final</version>   <!-- use the latest 7.x release -->
    </dependency>
    <!-- The JDBC driver: PostgreSQL here; H2 or MySQL work the same way -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.7.14</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Note the group ID: Hibernate moved from org.hibernate to org.hibernate.orm with version 6, and Hibernate 6 and later use jakarta.persistence imports only. If you see javax.persistence in a project, it uses Hibernate 5 or older. In a Spring Boot project you add spring-boot-starter-data-jpa instead, which brings Hibernate and configures it from application.properties (Spring Data JPA).

Configuration with persistence.xml

Plain JPA reads its configuration from META-INF/persistence.xml on the classpath (in a Maven project: src/main/resources/META-INF/persistence.xml). It defines one or more persistence units: a name, the entity classes and the connection settings.

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="library" transaction-type="RESOURCE_LOCAL">
        <class>com.example.library.Author</class>
        <class>com.example.library.Book</class>

        <properties>
            <!-- Standard JPA connection properties -->
            <property name="jakarta.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/library"/>
            <property name="jakarta.persistence.jdbc.user" value="library"/>
            <property name="jakarta.persistence.jdbc.password" value="${env.DB_PASSWORD}"/>

            <!-- Schema generation: none | create | drop-and-create | drop -->
            <property name="jakarta.persistence.schema-generation.database.action" value="none"/>

            <!-- Hibernate-specific: print SQL while developing -->
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.highlight_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

A few notes on these settings:

  • transaction-type="RESOURCE_LOCAL" means you manage transactions yourself with em.getTransaction() (Java SE, Spring). Inside a Jakarta EE application server you use JTA and a server-managed data source instead.
  • The dialect is detected automatically. Older tutorials set hibernate.dialect; since Hibernate 6 it reads the database type and version from the JDBC connection, and you should normally leave the property out.
  • Placeholders like ${env.DB_PASSWORD} are not standard JPA. Shown here as a reminder: never commit real passwords. In plain JPA, pass secrets as a property map to Persistence.createEntityManagerFactory("library", props); Spring Boot reads them from the environment for you.
  • List your entity classes with <class> in Java SE. Automatic scanning is guaranteed only inside application servers and frameworks like Spring.

Schema generation: convenient, and dangerous

Hibernate can create tables from your entities. The standard property jakarta.persistence.schema-generation.database.action and the older Hibernate property hibernate.hbm2ddl.auto control it:

Value (hbm2ddl.auto) Effect Use it for
create-drop create the schema at startup, drop it at shutdown tests with an in-memory database
create drop and recreate at startup throwaway local experiments
update add missing tables and columns, never remove anything quick prototypes only
validate check that tables and columns match the entities, fail if not production, as a safety check
none do nothing production with migrations

Never let Hibernate create or alter a production schema. create deletes all data on restart, and update cannot rename columns, migrate data or drop anything, so the schema slowly drifts from what you think it is. Production schemas belong to a migration tool such as Flyway or Liquibase, with versioned SQL scripts reviewed like code; validate then confirms that the entities and the migrated schema agree.

Bootstrapping in code

With a persistence.xml on the classpath, you create the factory by unit name. Jakarta Persistence 3.2 also added a fully programmatic option, PersistenceConfiguration, that needs no XML, and helper methods that run a block of code in a transaction:

Java
// Classic: reads META-INF/persistence.xml
EntityManagerFactory emf = Persistence.createEntityManagerFactory("library");

// Jakarta Persistence 3.2+: no XML file at all
EntityManagerFactory emf2 = new PersistenceConfiguration("library")
    .managedClass(Author.class)
    .managedClass(Book.class)
    .property("jakarta.persistence.jdbc.url", "jdbc:h2:mem:library")
    .property("jakarta.persistence.schema-generation.database.action", "drop-and-create")
    .createEntityManagerFactory();

// Jakarta Persistence 3.2+: begin, commit, or roll back on exception, then close the EntityManager
emf.runInTransaction(em -> em.persist(new Author("Chinua Achebe")));
long count = emf.callInTransaction(em ->
    em.createQuery("SELECT count(a) FROM Author a", Long.class).getSingleResult());

emf.close();   // at application shutdown

The EntityManagerFactory is expensive to build (it reads all mappings and creates the connection pool) and thread-safe: create one per database per application and keep it for the application's lifetime. An EntityManager is cheap and not thread-safe: create one per unit of work (for example per request or per transaction) and close it afterwards.

Your first entity

An entity is a class annotated with @Entity whose instances are stored as rows. Here is a realistic one, with the most common annotations:

Java
package com.example.library;

import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDate;

@Entity
@Table(name = "books",
       uniqueConstraints = @UniqueConstraint(name = "uk_books_isbn", columnNames = "isbn"),
       indexes = @Index(name = "ix_books_title", columnList = "title"))
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 200)
    private String title;

    @Column(length = 17, nullable = false)
    private String isbn;

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

    @Column(name = "published_on")
    private LocalDate publishedOn;

    @Enumerated(EnumType.STRING)
    @Column(length = 20, nullable = false)
    private Format format = Format.PAPERBACK;

    @Transient
    private boolean selectedInUi;           // not stored

    protected Book() { }                    // for JPA

    public Book(String title, String isbn) {
        this.title = title;
        this.isbn = isbn;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    // other getters and setters ...
}

public enum Format { HARDCOVER, PAPERBACK, EBOOK }

With PostgreSQL, Hibernate would generate roughly this table for it:

SQL
create table books (
    id bigint generated by default as identity,
    title varchar(200) not null,
    isbn varchar(17) not null,
    price numeric(8,2),
    published_on date,
    format varchar(20) not null,
    primary key (id),
    constraint uk_books_isbn unique (isbn)
);
create index ix_books_title on books (title);

The mapping annotations

@Entity marks the class as persistent. Its optional name sets the entity name used in JPQL queries (default: the simple class name, Book). Don't confuse it with the table name.

@Table sets the table name (default: the entity name), plus schema, unique constraints and indexes. The constraints and indexes only matter when Hibernate generates the schema, but they also document the design.

@Id marks the primary key field. Every entity needs one. Use a wrapper type such as Long rather than long: null then clearly means "not saved yet".

@Column customizes the column. Without it, every non-static, non-transient field is mapped to a column with the field's name (Spring Boot additionally converts publishedOn to published_on by default; plain Hibernate does not).

@Column attribute Meaning Default
name column name the field name
nullable add NOT NULL to generated DDL true
length size of VARCHAR columns 255
precision, scale digits for DECIMAL/NUMERIC database-dependent
unique single-column unique constraint false
insertable, updatable leave the column out of INSERT / UPDATE statements true
columnDefinition raw SQL type fragment (not portable) none

nullable = false and length = 200 are schema hints, not validation. They shape generated DDL; they don't stop your code from setting a 300-character title. If the database column has the constraint, the insert fails with an exception at flush time; if it doesn't, nothing checks at all. Validate input with Jakarta Bean Validation (@NotBlank, @Size(max = 200)), covered in Validation and Error Handling, and keep the real constraints in your migrations.

@Transient excludes a field from persistence (Java's transient keyword does the same, but also affects serialization). @Enumerated controls how enums are stored, and its default is a trap you'll see in a moment. @Lob marks large text or binary data (CLOB/BLOB). Types such as String, the primitives and their wrappers, BigDecimal, UUID, byte[] and the java.time classes (LocalDate, LocalDateTime, Instant, OffsetDateTime) are mapped automatically. Avoid java.util.Date and Calendar in new code.

Mapping by annotation, demonstrated

To see how a provider turns those annotations into SQL, the next program defines its own small annotations with the same names and meanings as the JPA ones (they are not the real jakarta.persistence types, which aren't on this classpath), reads them with reflection, generates the DDL, and inserts objects while setting their generated IDs, exactly as persist does with an identity column.

Java Annotation-driven mapping, by hand

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.

The generated DDL follows the annotations: the table is called books, the ISBN column is isbn_13, the title is VARCHAR(200) NOT NULL, and the @Transient field is gone. After persist, the object carries the ID the database generated. And the NOT NULL failure shows the warning above in action: the constraint protected the data only because it existed in the database, and the problem surfaced only when the SQL ran (H2's SQLState 23502 means "null not allowed").

Choosing an ID strategy

@GeneratedValue tells JPA that the database or provider assigns the key. The strategy decides how:

Strategy How the ID is produced Notes
IDENTITY an auto-increment / identity column; the database assigns it during INSERT simple and common with MySQL; Hibernate must insert immediately on persist and cannot batch inserts
SEQUENCE a database sequence, read before the insert the best choice on PostgreSQL, Oracle, SQL Server, H2; supports batching; with allocationSize one round trip covers many IDs
UUID (JPA 3.1+) a random UUID generated in Java no database round trip; IDs are unique across systems but larger and less index-friendly
TABLE a row in a special table, updated with locks portable but slow; avoid
AUTO (default) the provider decides Hibernate picks a sequence; on databases without sequences (MySQL) it emulates one with a table, which is slow, so choose IDENTITY there explicitly

A sequence with an allocation size looks like this:

Java
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_seq")
@SequenceGenerator(name = "book_seq", sequenceName = "book_seq", allocationSize = 50)
private Long id;

The allocationSize (default 50) must match the sequence's INCREMENT BY in the database. Hibernate reads one sequence value and then hands out the next 50 IDs from memory. The program below compares how many database round trips 120 new entities need with each strategy, using a real H2 sequence for the pooled case.

Java Database round trips per ID strategy

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.

The identity column needs a round trip for every single entity, because the key exists only after the row does. The sequence needs three reads for 120 IDs (each read reserves a block of 50) plus three batched inserts. This simulation gives each block the 50 values starting at the sequence value; Hibernate's built-in optimizers use slightly different arithmetic, but the cost is the same. For write-heavy tables, that difference matters: batching requires a sequence or UUID, and it also requires hibernate.jdbc.batch_size to be set.

Rules for entity classes

JPA places a few requirements on entity classes, mostly because the provider creates instances by reflection and may create proxy subclasses for lazy loading:

  • The class must have a public or protected no-argument constructor. It may have others too.
  • The class must not be final, and persistent methods must not be final, or Hibernate can't proxy them.
  • It must be a top-level class (or a static nested class) annotated with @Entity, and it needs an @Id.
  • Serializable is not required, though it's useful if entities are stored in HTTP sessions or caches.
  • Records can't be entities: they are final, immutable and have no no-argument constructor. They are excellent for value objects mapped with @Embeddable (supported for records by Hibernate 6.2+ and Jakarta Persistence 3.2) and for read-only query results (DTO projections).

Field or property access? Where you put @Id decides how JPA reads and writes state. On a field, Hibernate uses the fields directly (field access) and you can write getters and setters freely, including ones that validate or compute. On a getter, it calls getters and setters (property access). Field access is the common, simpler choice; don't mix the two in one class without @Access.

The enum trap

@Enumerated defaults to EnumType.ORDINAL, which stores the constant's position (0, 1, 2...). It is compact, and it breaks silently the day someone inserts a new constant in the middle of the enum. The program below stores ordinals with one version of an enum, then reads the same rows with the next version.

Java Why EnumType.STRING beats ORDINAL

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.

After the new constant was added, every shipped order reads as PAID and every delivered one as SHIPPED. Nothing fails; the data just means something else now. With EnumType.STRING the names are stored and all three rows are still correct. Always write @Enumerated(EnumType.STRING) (and never rename a constant without a migration), or use an AttributeConverter to store stable codes such as "P", "S", "D".

equals and hashCode for entities

Entities have identity in the database (the primary key) and in Java (the object). With generated IDs, the key doesn't exist until the entity is persisted, which breaks the usual "compare the ID" implementation inside hash-based collections:

Java An entity that gets lost in a HashSet

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.

The naive version fails twice. Two different unsaved books are "equal" because both IDs are null, so a Set would keep only one of them. And once the ID is assigned, the book's hash code changes, so the set looks in the wrong bucket and can neither find nor remove the object it contains. The safe version is the widely used pattern for entities with generated IDs: equal only when both have the same non-null ID (or are the same object), with a constant hash code. A constant hash code makes hash lookups slower for huge sets, which is an acceptable price for collections of entities. If an entity has a natural, immutable business key (an ISBN, an email address that never changes), comparing that key is even better.

The persistence context in practice

Everything you do through an EntityManager goes through its persistence context (also called the first-level cache), which you met in the previous lesson. With a real Hibernate setup you would see it like this:

Java
emf.runInTransaction(em -> {
    Book dune = new Book("Dune", "978-0441172719");
    em.persist(dune);                       // managed now; with IDENTITY the INSERT runs immediately

    Book same = em.find(Book.class, dune.getId());
    System.out.println(same == dune);       // true: no SELECT, served from the context

    dune.setTitle("Dune (40th anniversary)");   // no method call needed...
    em.createQuery("SELECT b FROM Book b WHERE b.title LIKE 'Dune%'", Book.class)
      .getResultList();                     // ...flush runs the UPDATE before this query (FlushMode.AUTO)
});                                         // commit: flush remaining changes, then COMMIT

Three behaviors to keep in mind:

  • One instance per row within an EntityManager. Different EntityManagers (for example two HTTP requests) get different instances of the same row.
  • Changes are flushed automatically: at commit, and with the default FlushMode.AUTO also before a query whose results could be affected by pending changes. em.flush() forces it.
  • The context grows with every entity you load. In a batch job that processes 100,000 rows, call em.flush() and em.clear() every few hundred entities, or memory fills up and dirty checking slows down.

The full lifecycle (new, managed, detached and removed states, merge, and optimistic locking) is the topic of Entity Lifecycle and Transactions.

Seeing the SQL

hibernate.show_sql=true prints statements to standard output, which is enough for a first experiment. In a real application, configure logging instead, so the SQL goes through your logging framework (Logging with SLF4J and Logback):

PROPERTIES
# SQL statements (Hibernate 6+ logger names)
logging.level.org.hibernate.SQL=DEBUG
# The values bound to the ? placeholders
logging.level.org.hibernate.orm.jdbc.bind=TRACE

Keep it on while you develop. Every surprise in this chapter, from an unexpected UPDATE to 500 queries for one page, is obvious in the SQL log and invisible without it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which hibernate.hbm2ddl.auto setting is appropriate for a production database whose schema is managed by Flyway migrations?

    Migrations own the production schema. validate only checks that entities and tables match and fails fast if they don't; it never changes anything.
  2. 2. An entity has @Column(nullable = false, length = 50) String name;. Your code sets a 60-character name. What prevents it from being saved?

    @Column attributes are used for schema generation. Validation needs @Size/@NotNull with Bean Validation, and the database constraint is the last line of defense.
  3. 3. Why does Hibernate insert an entity immediately on persist when it uses GenerationType.IDENTITY?

    The database assigns identity values during INSERT, so Hibernate has to run it right away. That also prevents JDBC batching of inserts.
  4. 4. Orders were saved with the default @Enumerated mapping. Later a constant is added in the middle of the enum. What happens to existing rows?

    The default is ORDINAL, which stores positions. Inserting a constant shifts every later position, so old data silently changes meaning. Use EnumType.STRING.
  5. 5. Which statement about EntityManagerFactory and EntityManager is correct?

    The factory is costly to build and thread-safe. EntityManagers are cheap, hold a persistence context and must not be shared between threads.

Summary

  • Add org.hibernate.orm:hibernate-core (Hibernate 7 implements Jakarta Persistence 3.2) plus a JDBC driver; use jakarta.persistence imports.
  • Configure a persistence unit in META-INF/persistence.xml (connection, entity classes, properties) or programmatically with PersistenceConfiguration. Leave the dialect out; Hibernate detects it.
  • Let Hibernate generate schemas only for tests. Production schemas come from Flyway or Liquibase, checked with validate.
  • Build one EntityManagerFactory per application; use a short-lived EntityManager per unit of work. runInTransaction and callInTransaction handle commit and rollback.
  • Map entities with @Entity, @Table, @Id, @GeneratedValue, @Column, @Enumerated(EnumType.STRING) and @Transient. @Column constraints are DDL hints, not validation.
  • Prefer SEQUENCE IDs (with an allocationSize matching the sequence) where the database supports them; IDENTITY is simple but disables insert batching; UUID needs no round trip.
  • Entities need a no-argument constructor and must not be final; records can't be entities but suit embeddables and DTOs. Base equals on a non-null ID with a constant hashCode.
  • The persistence context keeps one instance per row and flushes changes automatically; log the SQL while you develop.

Next: Entity Relationships maps one-to-many, many-to-one, one-to-one and many-to-many associations, and shows the tables behind them.