Hibernate Basics

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.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.

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 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.

Hibernate BLOB and CLOB Mapping With @Lob (Hibernate 7)

Map BLOB and CLOB columns in Hibernate 7 with @Lob on byte[], String, Blob and Clob fields. See the generated column types on H2, MySQL and PostgreSQL, how to stream large files with Blob, and why @Basic(fetch = LAZY) needs bytecode enhancement.

getReference vs find: JPA EntityManager Methods Compared

EntityManager find() loads an entity with a SELECT or returns null, while getReference() returns a proxy without SQL. See when each runs SQL, when EntityNotFoundException and LazyInitializationException are thrown, and how to set a foreign key without loading the entity.

Hibernate @NaturalId: Natural Ids, Lookups and Caching

Map a natural id such as a license plate with Hibernate’s @NaturalId, load entities with em.find(…, KeyType.NATURAL), handle mutable and composite natural ids, and cache lookups with @NaturalIdCache, with the SQL and statement counts from Hibernate 7.4.

Hibernate Second Level Cache: How It Works (With Ehcache)

The Hibernate second level cache shares entity data across all sessions of an EntityManagerFactory. Learn the lookup order, what the cache stores, the concurrency strategies, collection and query caching, statistics and eviction with Hibernate 7.4 and Ehcache 3.

Hibernate First Level Cache: Persistence Context Explained

The Hibernate first level cache is the persistence context of one EntityManager. See with counted SQL on Hibernate 7.4 when find() and queries hit the database, how detach(), evict(), clear() and refresh() work, and how to keep long transactions small.

Hibernate Insert: persist(), merge() and HQL Insert Examples

To insert an object with Hibernate, we pass a new entity to persist() inside a transaction. Learn when the INSERT runs for IDENTITY, SEQUENCE and assigned ids, how merge() and HQL insert statements work, and what replaced Session.save() in 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.