Hibernate

Hibernate ORM enables developers to more easily write applications whose data outlives the application process. As an Object/Relational Mapping (ORM) framework, Hibernate is concerned with data persistence as it applies to relational databases (via JDBC).

Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. Hibernate’s primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from manual result set handling and object conversion. Applications using Hibernate are portable to supported SQL databases with little performance overhead.

In addition to its own “native” API, Hibernate is also an implementation of the Java Persistence API (JPA) specification. As such, it can be easily used in any environment supporting JPA including Java SE applications, Java EE application servers, Enterprise OSGi containers, etc.

Hibernate supports lazy initialization, numerous fetching strategies and optimistic locking with automatic versioning and time stamping. Hibernate requires no special database tables or fields and generates much of the SQL at system initialization time instead of at runtime. Hibernate consistently offers superior performance over straight JDBC code, both in terms of developer productivity and runtime performance.

Hibernate was designed to work in an application server cluster and deliver a highly scalable architecture. Hibernate scales well in any environment: Use it to drive your in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands. Hibernate is well known for its excellent stability and quality, proven by the acceptance and use by tens of thousands of Java developers.

Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java Annotations.

Read below java tutorials for understanding various concepts involved into hibernate.

Related Tags

Tutorials

Hibernate Search with Lucene and Spring Boot 4 Example

Add full-text search to a Spring Boot 4 application with Hibernate Search 8.4 and Lucene: map the entity, register the analyzer as a Spring bean, index existing rows on ApplicationReadyEvent, and expose a paged, sorted REST search endpoint tested with MockMvc.

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.

Mock JNDI DataSource in JUnit Tests with Hibernate and H2

Test code that looks up a JNDI DataSource without an application server: register a small in-memory JNDI provider or Simple-JNDI, bind an H2 DataSource under the production name, bootstrap Hibernate 7 with it and run CRUD in JUnit 6. Or skip JNDI and pass the DataSource object.

Hibernate Batch Insert and Update: batch_size Explained

Hibernate sends inserts, updates and deletes in JDBC batches once hibernate.jdbc.batch_size is set. Measured on Hibernate 7.4: why IDENTITY ids stop batching, how flush() and clear() keep memory flat, and when to use order_inserts, StatelessSession or a JPQL bulk statement.

Hibernate Aggregate Functions: count, min, max, sum, avg

Hibernate aggregate functions compute one value from many rows. Learn count, min, max, sum and avg in HQL, JPQL and the Criteria API, their Java return types, group by, having, null handling and Hibernate’s listagg, filter and window functions.

Hibernate Search: Full-Text Search with Lucene Example

Hibernate Search adds full-text search to Hibernate entities. Map fields with @FullTextField, @KeywordField and @GenericField, let the index follow every commit, rebuild it with the MassIndexer, and search with match, phrase, bool, range, sorting, paging and highlighting on Hibernate Search 8.4 and Lucene.

Hibernate Interceptor: Audit Trail and StatementInspector

A Hibernate interceptor gets a callback when an entity is persisted, changed, removed or loaded, with the old and new property values. Build an audit trail with onPersist, onFlushDirty and onRemove in Hibernate 7, pick the right scope, and rewrite SQL with a StatementInspector.

Hibernate Pagination: Offset, Keyset and Count Queries

Hibernate pagination loads a query result one page at a time with setFirstResult() and setMaxResults(). See the SQL for offset and keyset pages, page counts, the ORDER BY trap, join fetch paging and ScrollableResults on Hibernate 7.4.

JPA Lifecycle Callbacks in Hibernate: @PrePersist and More

The seven JPA lifecycle callbacks in Hibernate 7.4, when each one runs relative to persist(), flush and commit, entity listeners and default listeners in orm.xml, what a callback must not do, and Hibernate’s own event listeners.

Bootstrap EntityManager in Hibernate 7: 5 Ways With JPA 3.2

Create one EntityManagerFactory per database in Hibernate 7.4, from persistence.xml, from Java code with PersistenceConfiguration or HibernatePersistenceConfiguration, or from a PersistenceUnitInfo, then open one EntityManager per unit of work with runInTransaction() and callInTransaction().

Hibernate Date and Time Mapping: LocalDateTime and Instant

Hibernate maps LocalDate, LocalDateTime, Instant, OffsetDateTime and ZonedDateTime to SQL date, time and timestamp columns without annotations. See the DDL and stored values on Hibernate 7.4 and how @TimeZoneStorage keeps or drops the offset.

Configuring Ehcache 3 with Hibernate 6 and 7: Setup Guide

Set up Ehcache 3 as the Hibernate 6 and 7 second level cache: the hibernate-jcache and jakarta Ehcache dependencies, the JCache properties, a minimal ehcache.xml, @Cacheable and @Cache, hit statistics, and the startup error each missing piece causes.

Unable to Locate Persister in Hibernate: Causes and Fixes

“Unable to locate persister” (Unknown entity type in Hibernate 7) means Hibernate has no mapping for the class it received. See each cause reproduced on Hibernate 7.4 and Spring Boot 4.1, from javax imports and missing registration to DTOs, proxies and entity scanning, with a tested fix for each.

Hibernate Validator CDI: Inject Validator with Weld SE

Hibernate Validator CDI lets the CDI container create the ValidatorFactory and Validator. Learn to inject them with Weld SE, use @Inject inside a ConstraintValidator, and get automatic method validation on CDI beans.

No Validator Could Be Found for Constraint: Fix HV000030

UnexpectedTypeException (HV000030) means a Bean Validation constraint sits on a type it cannot check, such as @NotBlank on an Integer. See every cause with the real message, a type-to-constraint grid, and the fix for numbers, dates, lists, Optional and your own types.

Hibernate.initialize(): Load a Proxy or a Lazy Collection

Hibernate.initialize() loads a lazy proxy or a lazy collection while the EntityManager is open, so the data is usable after the transaction ends. Examples with the SQL, unproxy(), size(), the closed-session error and the N+1 alternatives.

GenericJDBCException: Could Not Prepare Statement [Solved]

Hibernate throws GenericJDBCException: could not prepare statement when the driver rejects the SQL and gives no SQLState to classify it. See the real messages from SQLite, H2 and HSQLDB on Hibernate 7.4, how to read the root SQLException, and the fix for each cause.

Cannot Mix Named and Positional Parameters in Hibernate

Hibernate 4.3 to 5.2 throw QueryException: Cannot mix named and positional parameters when a stored procedure call registers parameters by name and by position. See the message in each version, what Hibernate 7.4 does with mixed HQL and native queries, and the fix.

Pure Native Scalar Queries Are Not Yet Supported: Fix

Hibernate 3.6 to 4.1 stop at startup with NotYetImplementedException when a named native query has no resultClass or resultSetMapping. See the real error, the @ColumnResult workaround and how Hibernate 7 returns scalar values.

Hibernate Criteria Query Guide: JPA CriteriaBuilder Examples

A Hibernate criteria query builds SQL from Java objects with CriteriaBuilder, CriteriaQuery and Root. Learn filters, joins, fetch joins, group by, subqueries, pagination, dynamic filters, bulk updates and the static metamodel in Hibernate 7, with the generated SQL for each query.

HQL Tutorial: Hibernate Query Language With Examples

Hibernate Query Language (HQL) queries entities and attributes instead of tables and columns. Learn HQL select, joins, join fetch, aggregates, subqueries, update, delete and insert in Hibernate 7, with the SQL Hibernate generates for each query.

Hibernate @Immutable: Read-Only Entities and Collections

Hibernate’s @Immutable annotation stops UPDATE statements for an entity, blocks changes to a collection and, since Hibernate 7, fails HQL update queries by default. We compare it with updatable = false, read-only queries, @Subselect and records.

Hibernate Lazy Loading: FetchType LAZY vs EAGER with SQL

Hibernate lazy loading reads an association only when the code first uses it. See the SQL that LAZY and EAGER run, how proxies and PersistentBag work, and how to fix LazyInitializationException with join fetch, entity graphs, Hibernate.initialize() or a DTO projection.

Hibernate merge vs refresh: Merging and Refreshing Entities

merge() copies a detached object onto a managed instance and returns that copy, while refresh() reloads a managed entity from its row and discards unsaved changes. See the SQL, the OptimisticLockException of an outdated merge, and what replaced Session.update() in Hibernate 7.

Hibernate save vs saveOrUpdate vs update: Hibernate 7 Guide

Hibernate save(), update() and saveOrUpdate() were deprecated in Hibernate 6 and removed in Hibernate 7. We run the old methods on Hibernate 6.6, then show how persist() and merge() replace them for new, detached and managed entities.

Hibernate equals and hashCode for Entities Across Sessions

Hibernate returns one object per row inside a session but a new object in every other session. Implement equals() and hashCode() for entities with a generated id, a business key or a UUID, make them proxy-safe, and avoid Lombok @Data.

Hibernate c3p0 Connection Pool Setup with Spring Boot 4

Configure c3p0 as Hibernate 7’s connection pool with hibernate.c3p0 settings, check it in the logs and with pool statistics, size it, close and test idle connections, find leaks, and use c3p0 as the DataSource in Spring Boot 4.

Hibernate In-memory Database for JUnit Tests with H2

Unit test Hibernate repositories against an in-memory H2 database with JUnit 6: one EntityManagerFactory per test class, data from import.sql, a fresh copy of the data before every test with truncate(), and the H2 settings and pitfalls that break tests.

Hibernate SessionFactory: 5 Ways to Build It in Hibernate 7

Build a Hibernate SessionFactory in Hibernate 7.4 with HibernatePersistenceConfiguration, the native StandardServiceRegistryBuilder and MetadataSources API, the Configuration class, hibernate.cfg.xml, or unwrap() from an EntityManagerFactory. Then share one factory across threads and close it at shutdown.

Bean Property configurationClass Is Not Writable [Solved]

Spring throws “Bean property ‘configurationClass’ is not writable” when XML written for Hibernate 3 sets configurationClass on a newer LocalSessionFactoryBean. See the real error on Spring 7, the XML fix, and the Spring Boot 4 setup that needs no SessionFactory bean.

Fix NoClassDefFoundError: org/hibernate/cache/CacheProvider

NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider means a Hibernate 3 class (Spring’s orm.hibernate3 factory bean or an old Ehcache provider) runs with Hibernate 4 or newer. Here is the fix for old projects and the Hibernate 7 JCache setup.

NoClassDefFoundError SessionFactoryImplementor in Hibernate

NoClassDefFoundError: org/hibernate/engine/SessionFactoryImplementor means a class built for Hibernate 3, usually Spring’s orm.hibernate3 transaction manager, runs with Hibernate 4 or newer. Find the jar, switch to the matching Spring package or align the Hibernate modules, and unwrap the SPI interface on Hibernate 7.

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.