
How to Use Hibernate Natural Ids and Business Keys
Use Hibernate natural ids and business keys: map @NaturalId, look up by business key with caching, implement equals and hashCode safely and add constraints.
Tag
223 posts

Use Hibernate natural ids and business keys: map @NaturalId, look up by business key with caching, implement equals and hashCode safely and add constraints.

Run bulk update and delete queries in JPA and Spring Data, clear the stale persistence context, keep versions right and delete huge tables in chunks.

Use DTO projections with Hibernate and Java records: constructor expressions in JPQL, Spring Data interface and class projections, and when to skip entities.

Implement multi tenancy with Hibernate: compare discriminator, schema and database per tenant, resolve the tenant per request and avoid cross tenant leaks.

Use optimistic locking with a JPA version column: map @Version, handle OptimisticLockException, retry safely and expose the version through a REST API.

Find and fix a slow SQL query behind a Java service: capture the statement, run EXPLAIN ANALYZE, read scans and joins, then add an index or rewrite it.

Write a logging aspect with Spring AOP: add the starter, define pointcuts for services, log arguments, results and failures, and avoid leaking data.

Write a correct Java microbenchmark with JMH: project setup, state classes, Blackhole, warmup, forks, avoiding dead code elimination and reading the results.

Use Kafka exactly once semantics in Java: the idempotent producer, transactions for consume transform produce, isolation level and what it cannot cover.

Handle duplicate and out of order messages: a processed message table, natural keys, versioning and a design that ignores delivery order.

Use PESSIMISTIC_WRITE and SKIP LOCKED in JPA and Spring Data, set lock timeouts, handle lock exceptions and know when optimistic locking is the better choice.

Publish events reliably with the outbox pattern: write an outbox row in the same transaction and stream it to Kafka with Debezium change data capture.