Hibernate Tutorials: Learn Hibernate 7 with Examples

Hibernate tutorials for Hibernate 7.4, Jakarta Persistence 3.2 and Java 25, grouped as a learning path: setup, entities, entity states, associations, queries, caching, validation, search and fixes for common errors.

Jakarta_EE

Hibernate is a Java persistence framework that maps Java classes to database tables and writes the SQL for us. It implements the Jakarta Persistence (JPA) standard, so our code uses the standard EntityManager API, and Hibernate adds its own features on top.

We use Hibernate to store and load Java objects in a relational database without writing JDBC code for every table. For example, a notes app saves a note from a web form with one persist() call and lists the notes of a user with one query. These Hibernate tutorials use Hibernate 7.4, Jakarta Persistence 3.2 and Java 25, and each one links a runnable Maven project.

The following example adds the two Maven dependencies that every tutorial uses, starts Hibernate and saves one entity.

<dependency>
  <groupId>org.hibernate.orm</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>7.4.11.Final</version>
</dependency>
<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <version>2.5.252</version>
</dependency>
SessionFactory sessionFactory = new HibernatePersistenceConfiguration("notes")
    .managedClass(Note.class)
    .jdbcUrl("jdbc:h2:mem:notes")
    .jdbcCredentials("sa", "")
    .schemaToolingAction(Action.CREATE_DROP)
    .showSql(true, false, false)
    .createEntityManagerFactory();

sessionFactory.runInTransaction(em -> em.persist(groceries));
// insert into Note (created_on,text,title,id) values (?,?,?,default)

Notice that we write no SQL ourselves, and Hibernate prints the INSERT it sends.

Next, we list the tutorials by topic, from the first setup to the common errors, in the order a new project needs them.

1. How to Learn Hibernate

We grouped the tutorials in the order a new project needs them. The first four groups cover the basics, and we can read the rest when a project needs them.

Learning path with eight boxes: 1 Setup (hello world, bootstrap, H2 test setup), 2 Entities (@Entity, @Column, dates, LOBs, ids), 3 Entity states (persist, merge, remove, find, callbacks), 4 Associations (one-to-many, many-to-many, cascade, lazy), 5 Queries (HQL, Criteria, native SQL, paging), 6 Performance (first and second level cache, batching), 7 Integrations (Validator, Search, Spring Boot), 8 Errors
Steps 1 to 4 are the basics every Hibernate project needs; steps 5 to 8 can be read in any order.

2. Getting Started

These articles set up Hibernate and the test database that the other tutorials build on.

3. Entities and Mapping Annotations

An entity is a Java class mapped to a table. These tutorials cover the annotations on its fields and the column types they produce.

4. Entity States and the Persistence Context

Hibernate tracks each loaded entity in the persistence context, and the state of an entity decides what SQL a call sends.

5. Associations

Associations connect entities through foreign keys. We start with the overview, then read the article for the relationship we need.

6. Querying Data

Hibernate queries come as HQL strings or as type-safe Criteria API objects, and we can always fall back to plain SQL.

7. Caching and Performance

These tutorials reduce the number of SQL statements and round trips an application sends.

Hibernate Validator and Hibernate Search are separate projects that plug into Hibernate ORM.

9. Common Hibernate Errors

Each error article reproduces the message on a real project and shows the cause together with the fix.

Error messageUsual cause
Unable to locate persisterThe class is not registered as an entity
No row with the given identifier existsA proxy or foreign key points to a missing row
Errors in named queriesA @NamedQuery uses a table name or a wrong attribute
GenericJDBCException: could not prepare statementThe database rejects the SQL, for example a missing table or a reserved word
Cannot mix named and positional parametersOne query or procedure call uses both parameter styles
Invalid character value for castText sent to a number column in HSQLDB
No validator could be found for constraintA constraint on a type it cannot check
Pure native scalar queries are not yet supportedA native named query without a result mapping on Hibernate 4.1 or older
Bean property configurationClass is not writableHibernate 3 Spring XML used with a newer Spring
NoClassDefFoundError: CacheProviderA Hibernate 3 cache jar with Hibernate 4 or later
NoClassDefFoundError: SessionFactoryImplementorA library built for Hibernate 3 with Hibernate 4 or later

10. Hibernate Tutorials FAQs

10.1. What changed in Hibernate 7 for code from older tutorials?

Hibernate 7 removed several APIs that Hibernate 5 and 6 tutorials use, and these articles use the replacements instead.

Old APIHibernate 7 replacement
*javax.persistence.***jakarta.persistence.**
session.save(), update(), saveOrUpdate()persist() and merge()
session.load()getReference()
session.createCriteria()CriteriaBuilder
EmptyInterceptorThe Interceptor interface with default methods
@Where@SQLRestriction or @SoftDelete
hibernate.cache.provider_classhibernate.cache.region.factory_class with JCache

10.2. Should we learn Hibernate or JPA?

We learn both. JPA (now Jakarta Persistence) is the standard API, and Hibernate implements it. These tutorials use the standard EntityManager API wherever it exists and show the Hibernate-specific features, such as @SoftDelete and @NaturalId, where the standard has no equivalent.

10.3. Do these tutorials need Spring Boot?

No. Most examples start Hibernate with HibernatePersistenceConfiguration and an H2 database, so they run with mvn test and nothing else. The Spring Boot articles say so in their titles, and the same mappings and queries work unchanged inside a Spring Boot application.

11. Conclusion

We recommend starting with the hello world example and the bootstrapping articles, then learning entities, entity states and associations in that order. Queries, caching, validation and the error articles can wait until a project needs them.

12. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.