Hibernate

31 posts in this section

@MappedSuperclass: Sharing Fields Without Inheritance Tables

Introduction Almost every entity in a real application shares a few common fields: id, createdAt, updatedAt, and perhaps version. Writing these in every entity class is repetitive and error-prone. @MappedSuperclass lets you define them once in a base class that all entities extend — without creating a parent table or any inheritance mapping in the database. What Is @MappedSuperclass? @MappedSuperclass marks a class whose field mappings are inherited by subclass entities.

Continue reading »

@Transactional in Depth: Propagation, Isolation, and Rollback

What @Transactional Does @Transactional tells Spring to wrap the annotated method in a database transaction. Spring opens the transaction before the method starts and commits (or rolls back) when it ends. The annotation works via an AOP proxy — understanding this proxy model is essential for avoiding the most common @Transactional bugs. The AOP Proxy Model Spring creates a proxy around your bean. When code outside the bean calls a @Transactional method, the call goes through the proxy, which manages the transaction:

Continue reading »

Auditing: @CreatedDate, @LastModifiedBy, and Hibernate Envers

Why Auditing Matters Production systems must answer: “Who changed this? When? What did it look like before?” Without auditing infrastructure, you add created_at, updated_at, created_by, updated_by columns manually to every entity — dozens of lines of boilerplate repeated everywhere. Spring Data JPA auditing fills these fields automatically. Hibernate Envers goes further: it captures every revision of every entity in separate audit tables. Spring Data JPA Auditing Enable Auditing @Configuration @EnableJpaAuditing(auditorAwareRef = "auditorProvider") public class JpaAuditingConfig { @Bean public AuditorAware<String> auditorProvider() { return () -> Optional.

Continue reading »

Basic Entity Mapping: @Entity, @Table, @Id, @Column

Introduction Entity mapping is the process of telling Hibernate how your Java class corresponds to a database table, and how each field maps to a column. JPA provides a rich set of annotations for this — from the minimal @Entity and @Id to the detailed @Column with constraints. This article covers every annotation and attribute you need to map entities precisely and confidently. @Entity @Entity marks a class as a JPA entity — a Java object that maps to a database table.

Continue reading »

Cascade Types and Orphan Removal: Managing Lifecycle Propagation

Introduction Cascade types control which persistence operations (save, merge, delete, refresh) propagate from a parent entity to its associated children. orphanRemoval controls what happens when a child is removed from the parent’s collection. Getting cascade wrong is one of the most common causes of unexpected deletes and data integrity issues in JPA applications. The Six Cascade Types cascade = CascadeType.PERSIST // propagate persist (save new entity) cascade = CascadeType.MERGE // propagate merge (re-attach detached entity) cascade = CascadeType.

Continue reading »

Custom Queries with @Query: JPQL and Native SQL

Why @Query Exists Derived query methods (Article 17) are great for simple conditions, but they break down fast. A method like findByOrderStatusAndCustomerCityAndPriceBetweenOrderByCreatedAtDesc is unreadable and still cannot express a JOIN or aggregation. @Query lets you write the exact JPQL or SQL you need, attached directly to a repository method — keeping your repository clean while giving you full query control. JPQL vs Native SQL JPQL Native SQL Language Entity/field names Table/column names Database portable Yes No JOIN FETCH Yes No Window functions No Yes Full-text search No Yes Complex analytics Limited Full power Start with JPQL.

Continue reading »

Custom Type Conversions: AttributeConverter and Enums

Introduction JPA handles most Java types automatically — String, Integer, LocalDate, BigDecimal. But what about a Java enum? A List<String> stored as JSON? A custom Money type? JPA’s AttributeConverter and @Enumerated let you control exactly how any Java type maps to a database column. Mapping Enums with @Enumerated Java enums are common in domain models. JPA maps them with @Enumerated: public enum OrderStatus { PENDING, CONFIRMED, SHIPPED, DELIVERED, CANCELLED } public enum ProductStatus { ACTIVE, INACTIVE, DISCONTINUED } @Column(length = 20, nullable = false) @Enumerated(EnumType.

Continue reading »

Derived Query Methods: Finding Data Without Writing SQL

Introduction Spring Data JPA can generate JPQL queries directly from method names. You declare a method like findByStatusAndPriceGreaterThan, and Spring Data parses the name, derives the query, and generates the implementation. No SQL, no @Query, no boilerplate. How Derived Query Parsing Works Spring Data JPA splits method names into a subject and a predicate: findBy Email And Status ↑ ↑ ↑ ↑ subject property operator property The subject determines the operation type (find, count, exists, delete).

Continue reading »

Dirty Checking, Flush Modes, and the First-Level Cache

The Persistence Context Revisited Article 3 introduced the persistence context — the in-memory cache of managed entities. This article goes deeper: how does the persistence context detect changes? When does it flush them to the database? And how can you tune this behaviour? Dirty Checking When you modify a managed entity, you don’t call save() or update(). You simply change the field: @Transactional public void giveDiscount(Long productId, BigDecimal discount) { Product product = productRepository.

Continue reading »

Embedded Types and Value Objects: @Embeddable and @Embedded

Introduction Not every concept in your domain deserves its own table. An Address — street, city, state, postal code — is a value object: it has no identity of its own, it belongs to an entity. JPA’s @Embeddable lets you model this as a separate Java class while storing it in the owning entity’s table. What Is an Embeddable? An @Embeddable class is a Java class whose fields are mapped to columns in the owning entity’s table — not a separate table.

Continue reading »