LESSON 23
MySQL & JPA Advanced
WEEK 05
31/07/2025 1
Inheritance in JPA Entities
31/07/2025 2
Introduction to Inheritance in JPA Entities
❖ Introduction to Inheritance in JPA Entities
❖ What is Inheritance in JPA?:
➢ JPA supports inheritance to model hierarchical entity classes, mapping Java OO inheritance to relational
databases.
➢ Allows subclasses to inherit fields and relationships from a superclass.
❖ Inheritance Strategies:
➢ @Inheritance(strategy = InheritanceType.SINGLE_TABLE): All classes in one table with discriminator.
➢ @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS): Separate table per concrete class.
➢ @Inheritance(strategy = InheritanceType.JOINED): Separate table for superclass and each subclass (1:1
relationship via shared primary key).
❖ Focus on 1:1 Inheritance:
➢ Refers to JOINED strategy, where subclass tables link 1:1 to superclass table using shared PK.
❖ Reference: JPA Inheritance Specification
31/07/2025 3
JOINED Inheritance Strategy (1:1 Mapping)
❖ Definition:
➢ Superclass has its own table; each subclass has a separate table with only subclass-specific
fields.
➢ Subclass tables reference superclass table via shared primary key (1:1 relationship).
❖ Annotations:
➢ @Inheritance(strategy = InheritanceType.JOINED) on superclass.
➢ @PrimaryKeyJoinColumn optional for customizing join column.
❖ Database Structure:
➢ Superclass table: Common fields + PK.
➢ Subclass table: Subclass fields + PK (foreign key to superclass PK).
❖ Explanation:
➢ Queries join tables as needed; supports polymorphism (e.g., querying superclass returns
mixed subclass instances).
31/07/2025 4
Example of 1:1 Inheritance in JPA
❖ Generated Tables:
➢ person: id (PK), name.
➢ student: id (PK/FK to person.id), major.
➢ teacher: id (PK/FK to person.id), subject.
❖ Explanation:
➢ Inserting a Student creates rows in both
person and student tables with same id.
➢ Query: SELECT p FROM Person p joins
tables to fetch mixed Student/Teacher
instances.
31/07/2025 5
Advantages and Disadvantages of 1:1 Inheritance
❖ Advantages:
➢ Normalized database: No redundant fields; easy to add new subclasses.
➢ Supports polymorphism: Queries on superclass return subclass instances.
➢ Efficient for reads on specific subclasses (no unnecessary joins).
❖ Disadvantages:
➢ Performance overhead: Joins required for superclass queries.
➢ Complex inserts/updates: Multiple tables involved.
➢ Not suitable for deep hierarchies due to join complexity.
❖ When to Use:
➢ When normalization is important and hierarchies are not too deep.
31/07/2025 6
Best Practices for 1:1 Inheritance in JPA
❖ Key Practices:
➢ Use @DiscriminatorColumn if needed for explicit type discrimination (though optional
in JOINED).
➢ Optimize queries with Fetch Joins to avoid N+1 issues.
➢ Index join columns for better performance.
➢ Test polymorphism: Ensure repositories handle superclass queries correctly.
❖ Common Pitfalls:
➢ Overusing joins in deep hierarchies leading to slow queries.
➢ Forgetting to generate IDs in superclass.
31/07/2025 7
JPA Entity Graphs
for Dynamic Fetching
31/07/2025 8
JPA Entity Graphs for Dynamic Fetching
❖ What is an Entity Graph?:
➢ Allows dynamic specification of which relationships to fetch (eager or
lazy) for a query.
➢ Overrides default @FetchType settings in entity mappings.
❖ Types:
➢ @NamedEntityGraph: Defined statically in entity class.
➢ Dynamic Entity Graph: Created programmatically via EntityManager.
❖ Explanation:
➢ Fetches department eagerly for findAll(), overriding LAZY.
➢ Avoids N+1 issues by specifying related data in a single query.
31/07/2025 9
JPA Entity Graphs for Dynamic Fetching
31/07/2025 10
JPA Entity Graphs for Dynamic Fetching
31/07/2025 11
JPA Entity Graphs for Dynamic Fetching
31/07/2025 12
JPA Projections
for Efficient Data Retrieval
31/07/2025 13
JPA Projections for Efficient Data Retrieval
❖ What are Projections?:
➢ Retrieve only specific fields from entities instead of the entire object.
➢ Implemented via interfaces or DTO classes to reduce data transfer.
❖ Types:
➢ Interface-based: Define an interface with getter methods for desired
fields.
➢ DTO-based: Use a custom class for complex projections.
❖ Explanation:
➢ Returns only id, name, and email, reducing data overhead.
➢ Works with Spring Data JPA’s query derivation or custom @Query.
31/07/2025 14
JPA Projections for Efficient Data Retrieval
31/07/2025 15
JPA Query Caching
with Second-Level Cache
31/07/2025 16
JPA Query Caching with Second-Level Cache
❖ What is Query Caching?:
➢ Caches query results to avoid repeated database hits for frequently executed
queries.
➢ Uses Hibernate’s second-level cache (L2 cache) with providers like EhCache.
❖ Setup:
➢ Enable L2 cache in application.properties:
▪ spring.jpa.properties.hibernate.cache.use_second_level_cache=true
▪ spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.E
hCacheRegionFactory
❖ Explanation:
➢ Caches query results and entities; subsequent calls retrieve from cache.
➢ Requires cache provider (e.g., EhCache) dependency in pom.xml.
31/07/2025 17
JPA Query Caching with Second-Level Cache
❖ Add @Cacheable to entities:
31/07/2025 18
JPA Query Caching with Second-Level Cache
❖ Query Cache Example:
31/07/2025 19
JPA Lifecycle Events and Listeners
31/07/2025 20
JPA Lifecycle Events and Listeners
❖ What are Lifecycle Events?:
➢ JPA triggers events during entity lifecycle: creation,
update, deletion, etc.
➢ Annotations: @PrePersist, @PreUpdate, @PostLoad,
@PostRemove, etc.
❖ Use Case:
➢ Automatically set creation/modification timestamps
or enforce business rules.
❖ Explanation:
❖ @PrePersist: Executes before saving a new entity.
❖ @PreUpdate: Executes before updating an
existing entity.
31/07/2025 21
JPA Native Queries
31/07/2025 22
JPA Native Queries
❖ What are Native Queries?:
➢ Execute raw SQL queries when JPQL is insufficient for complex operations.
➢ Map results to entities, DTOs, or scalar values.
❖ Types:
➢ Entity-mapped: Return managed entities.
➢ Scalar/DTO-mapped: Return custom objects or raw data.
❖ Explanation:
➢ nativeQuery = true: Indicates raw SQL instead of JPQL.
➢ Useful for database-specific features or complex joins.
31/07/2025 23
JPA Specifications
for Dynamic Queries
31/07/2025 24
JPA Specifications for Dynamic Queries
❖ What are Specifications?:
➢ Spring Data JPA feature to build dynamic, reusable query criteria.
➢ Uses Specification interface to define predicates for filtering.
❖ Use Case:
➢ Implement flexible search filters (e.g., search students by name, email, or
department).
❖ Explanation:
➢ JpaSpecificationExecutor: Enables repository to use Specification.
➢ Combine multiple specifications with and(), or() for complex filters.
31/07/2025 25
JPA Specifications for Dynamic Queries
31/07/2025 26
JPA Specifications for Dynamic Queries
31/07/2025 27
JPA Bulk Operations
31/07/2025 28
Introduction to JPA Bulk Operations
❖ Implementation:
➢ Use @Query with @Modifying in repository methods.
➢ JPQL for entity-based updates; native SQL for complex cases.
❖ Explanation:
➢ @Modifying: Indicates the query modifies data (UPDATE/DELETE).
➢ Returns number of affected rows.
➢ Use @Transactional in service layer to ensure atomicity.
31/07/2025 29
Introduction to JPA Bulk Operations
31/07/2025 30
Introduction to JPA Bulk Operations
31/07/2025 31
Soft Delete in JPA
31/07/2025 32
Introduction to Soft Delete in JPA
❖ What is Soft Delete?:
➢ Marks records as "deleted" (e.g., via a flag) instead of physically removing them.
➢ Preserves data for auditing, recovery, or compliance.
❖ Why Use Soft Delete with Filters?:
➢ Automatically excludes "deleted" records from queries without modifying each query.
➢ Implemented using Hibernate filters in JPA.
❖ Key Components:
➢ A deleted flag in the entity (e.g., boolean or timestamp).
➢ @Filter and @FilterDef annotations for global filtering.
❖ Benefits:
➢ Simplifies queries; maintains data integrity.
31/07/2025 33
Implementing Soft Delete with Filters
❖ Steps:
➢ Add a deleted field to the entity.
➢ Define @FilterDef and @Filter on the entity.
➢ Enable the filter in queries via EntityManager.
❖ Explanation:
➢ @FilterDef: Defines the filter with parameters.
➢ @Filter: Applies the condition (e.g., deleted = false).
➢ Enable filter per session for "active" records.
31/07/2025 34
Implementing Soft Delete with Filters
31/07/2025 35
Implementing Soft Delete with Filters
31/07/2025 36
Soft Delete Operations and Best Practices
❖ Soft Delete Operation:
➢ Set deleted = true instead of repository.delete().
❖ Restoring Records:
➢ Set deleted = false to "undelete".
❖ Best Practices:
➢ Use a timestamp for deletedAt for better auditing.
➢ Enable filter globally via interceptor or aspect for consistency.
➢ Combine with projections to exclude deleted field in responses.
❖ Pitfalls:
❖ Forgotten filter enablement leads to including "deleted" records.
❖ Performance impact on large datasets; index the deleted column.
31/07/2025 37
JPA Custom Converters
31/07/2025 38
Introduction to JPA Custom Converters
❖ What are Custom Converters?:
➢ Map non-standard Java types to database columns.
➢ Use @Converter to define custom conversion logic.
❖ Use Cases:
➢ Enums to strings, JSON to text, custom objects to blobs.
➢ Ensures type safety and portability.
❖ Types:
➢ AttributeConverter: Implements AttributeConverter<X, Y> for entity attributes.
➢ Auto-apply or explicit via @Convert.
31/07/2025 39
Implementing JPA Custom Converters
❖ Create enum
31/07/2025 40
Implementing JPA Custom Converters
❖ Create Converter
31/07/2025 41
Implementing JPA Custom Converters
❖ Apply to entity
31/07/2025 42
Conclusion and Next Steps
❖ Summary:
➢ Learned to build a CRUD application with Spring Boot, JPA, and MySQL.
➢ Covered entities, repositories, REST APIs, and basics JPA features.
❖ Next Steps:
➢ Build a full-stack application with a front-end (e.g., React).
❖ References:
➢ Spring Boot
➢ Spring Data JPA
➢ JPA Specification
31/07/2025 43