JPA Articles
Articles covering JPA relationship mapping, query methods, transactions, and performance optimization for data access design.
-
How to Use @NamedEntityGraph in Spring Data JPA - Reusable Fetch Definitions and Choosing Between EntityGraph.Type
This article explains how to stop writing @EntityGraph(attributePaths=...) on every method and instead define it once on the entity using @NamedEntityGraph for reuse. It covers how to write attributeNodes/subgraphs, the difference between LOAD and FETCH, applying it to a Repository, and the criteria for choosing between this and the ad-hoc version, all with code examples.
-
What is MyBatis? Understanding the Differences from JPA and a Minimal Spring Boot Setup
This article organizes what kind of O/R mapper MyBatis is by comparing its philosophy with JPA/Hibernate, and explains the criteria for choosing between them along with a minimal setup using mybatis-spring-boot-starter.
-
How to Use the @Query Annotation in Spring Boot + Spring Data JPA - From JPQL and Native SQL to Update Queries with @Modifying
A hands-on guide to mastering the @Query annotation in Spring Boot + Spring Data JPA. Covers the basics of JPQL and @Param, when to use nativeQuery=true, UPDATE/DELETE with @Modifying + @Transactional, countQuery when combined with Pageable, SpEL (:#{}), and escaping LIKE searches, all explained with copy-and-paste-ready repository code.
-
How to Persist enums to a Database with Spring Boot + JPA - Choosing Between @Enumerated(EnumType.STRING) and AttributeConverter
A guide to persisting enum fields to database columns with Spring Boot + JPA. Covers the difference between @Enumerated(STRING/ORDINAL), the dangers of ORDINAL, implementing an AttributeConverter for custom code values, and criteria for choosing between the two approaches, with practical examples.
-
How to Automatically Record Change History (Audit Logs) with Spring Boot + Hibernate Envers
A guide to implementing automatic recording of the full revision history of "who changed what, when, and how" in Spring Boot using Hibernate Envers. Covers _AUD table generation with @Audited, retrieving past versions with AuditReader, attaching user information to revisions, and strategies to prevent history table bloat.
-
How to Retrieve DTOs Directly with Spring Data JPA Projections - Choosing Between Interface-Based and Class-Based Projections
Learn how to SELECT only the columns you need and project them directly into DTOs/interfaces with Spring Data JPA projections. Compares interface-based, class-based (constructor), and dynamic projections through implementations, covering differences in the generated SQL, selection criteria, and pitfalls when combined with @Query.
-
How to Implement Pessimistic Locking (@Lock) with Spring Boot + JPA - PESSIMISTIC_WRITE and Deadlock Prevention
Learn how to apply PESSIMISTIC_WRITE/READ using Spring Data's JPA @Lock, verify the issuance of SELECT ... FOR UPDATE, control timeouts with jakarta.persistence.lock.timeout, avoid deadlocks, and choose between pessimistic and optimistic locking—explained with real code.
-
How to Load Initial Data with data.sql and schema.sql in Spring Boot - When to Use Flyway/Liquibase Instead
A guide to SQL initialization with schema.sql/data.sql in Spring Boot. It covers why data.sql doesn't get executed, spring.sql.init.mode, the execution order relative to Hibernate ddl-auto, configuring defer-datasource-initialization, and criteria for choosing Flyway/Liquibase in production.
-
How to Write Repository Layer Slice Tests with @DataJpaTest in Spring Boot - Choosing Between H2 and Testcontainers
A guide to writing slice tests focused on the Repository layer using @DataJpaTest in Spring Boot 3.x. Covers automatic rollback, TestEntityManager, switching between H2 and a real database via @AutoConfigureTestDatabase, verifying query methods and @Query, and when to combine Testcontainers — all with practical examples.
-
How to Reduce Boilerplate Code with Lombok in Spring Boot
A practical explanation of the roles and proper usage of Lombok annotations frequently used in Spring Boot development (@Data, @Builder, @RequiredArgsConstructor, @Slf4j, etc.). Also covers pitfalls when used with JPA Entity and how to combine it with constructor injection.
-
How to Implement Soft Delete with Spring Boot + JPA - Choosing Between @SQLDelete, @SQLRestriction, and Filters
Learn how to implement soft delete transparently with Spring Boot 3.x + Hibernate 6.4. We compare @SQLDelete + @SQLRestriction (formerly @Where) with @SoftDelete and @FilterDef so you can choose the right approach quickly, and cover common pitfalls such as unique constraint conflicts, restore operations, and recording who performed the deletion.
-
How to Implement Optimistic Locking (@Version) with JPA in Spring Boot to Prevent Concurrent Update Conflicts
Learn how to prevent 'Lost Update' issues that occur in e-commerce inventory updates and reservation systems using the @Version annotation. Covers OptimisticLockException handling, retry strategies with Spring Retry, and writing concurrency tests with practical code examples.
-
How to Implement Type-Safe Dynamic Queries with QueryDSL in Spring Boot
A practical guide to integrating QueryDSL into Spring Boot, covering Q-type class generation via APT, dynamic query implementation with JPAQueryFactory, and pagination integration. Includes a comparison with Specification.
-
How to Automate Entity-DTO Mapping with MapStruct in Spring Boot
An implementation guide for auto-generating toDto()/toEntity() methods with MapStruct instead of writing them by hand. Covers adding dependencies, basic @Mapper usage, nested objects, custom conversions, and unit testing.
-
Implementing REST API CRUD in Spring Boot - The Basic Controller, Service, and Repository Structure
A step-by-step guide to implementing REST API CRUD (Create, Read, Update, Delete) in Spring Boot using the three-layer Controller, Service, and Repository architecture. Get the four GET/POST/PUT/DELETE endpoints running with copy-paste code, and verify them end-to-end with curl.
-
How to Automatically Record Created and Updated Timestamps with JPA Auditing in Spring Boot
A guide to automatically recording entity creation and update timestamps using JPA Auditing in Spring Boot. Covers practical code for configuring @CreatedDate, @LastModifiedDate, @EnableJpaAuditing, and AuditorAware, including integration with Spring Security.
-
MyBatis vs JPA in Spring Boot: Selection Criteria and Combined Usage Patterns [With Comparison Table]
Not sure whether to choose MyBatis or JPA for your Spring Boot project? This article organizes a comparison table covering SQL control flexibility, learning cost, performance, and maintainability, along with a practical decision flowchart, the difference between #{} and ${}, and concrete configuration examples for using both together. Get all the decision criteria in one place.
-
Understanding Transaction Management with @Transactional in Spring Boot - Choosing Propagation and Isolation Levels
A comprehensive guide to transaction management using Spring Boot's @Transactional annotation, from fundamentals to practical application. Covers default behavior, the 7 propagation levels, the 4 isolation levels, and how to use them, along with solutions for common rollback failure patterns (checked exceptions, self-invocation) with real-world examples.
-
Spring Data JPA Query Methods: A Complete Naming Convention Cheat Sheet
A cheat sheet organizing Spring Data JPA query method naming conventions (findBy/existsBy/countBy/deleteBy) in reference tables. Check keywords like Containing/StartingWith/GreaterThan/Between/In/IsNull alongside the generated SQL and usage examples. Also covers custom queries with @Query, sorting, and paging with practical examples.
-
Introduction to JPA Association Mapping in Spring Boot - How to Use @OneToMany/@ManyToOne/@ManyToMany and mappedBy
A beginner-friendly guide to @OneToMany, @ManyToOne, @ManyToMany, and mappedBy in Spring Boot JPA. Covers bidirectional vs. unidirectional relationships, cascade, FetchType, the N+1 problem, and circular reference handling with code examples to resolve common pitfalls.