The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • 1. @Inheritance
  • About
  • Why Is It Needed?
  • Where @Inheritance is Used ?
  • Syntax of @Inheritance
  • Inheritance Strategies in JPA
  • 1. InheritanceType.SINGLE_TABLE
  • 2. InheritanceType.TABLE_PER_CLASS
  • 3. InheritanceType.JOINED
  • 2. @DiscriminatorColumn
  • About
  • Why is it Needed?
  • Where is @DiscriminatorColumn Used ?
  • Syntax
  • How It Works ?
  • Key Characteristics
  • Customizing @DiscriminatorColumn
  • When Not to Use @DiscriminatorColumn
  • Best Practices
  • 3. @DiscriminatorValue
  • About
  • Why is @DiscriminatorValue Needed?
  • Where is @DiscriminatorValue Used?
  • Syntax of @DiscriminatorValue
  • How It Works ?
  • Example
  • Characteristics of @DiscriminatorValue
  • Default Behavior of @DiscriminatorValue
  • Customizing @DiscriminatorValue
  • When Not to Use @DiscriminatorValue

Was this helpful?

  1. Spring
  2. Spring Features
  3. Spring Persistence
  4. JPA (Java Persistence API)
  5. ORM Mapping Annotations

4. Inheritance Mappings

1. @Inheritance

About

  • @Inheritance is an annotation used in JPA to define inheritance mapping strategies between entity classes.

  • It specifies how the inheritance between parent and child entity classes should be mapped into relational database tables.

Why Is It Needed?

  • In Java, it's natural to use class inheritance for code reuse and modeling hierarchy.

  • In relational databases, there is no native inheritance — every table is flat.

  • So JPA must simulate inheritance by deciding how to map the class hierarchy to tables.

Where @Inheritance is Used ?

When we have:

  • A base entity class (abstract or concrete).

  • Multiple subclasses extending the base.

  • We want the inheritance relationship persisted properly in DB.

Syntax of @Inheritance

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Parent {
    // fields
}
  • strategy is mandatory. It tells JPA which way to map the hierarchy.

Inheritance Strategies in JPA

There are 3 official strategies under @Inheritance(strategy = ...):

Strategy
Meaning

SINGLE_TABLE

One table for all classes.

TABLE_PER_CLASS

One table per concrete class.

JOINED

Multiple tables linked by primary keys.

1. InheritanceType.SINGLE_TABLE

  • All entities in the hierarchy are mapped into a single table.

  • One big table with columns from parent and child classes.

  • Discriminator column is used to differentiate which row belongs to which class.

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public class Employee {
    @Id
    private Long id;
    private String name;
}
@Entity
@DiscriminatorValue("manager")
public class Manager extends Employee {
    private String departmentName;
}
@Entity
@DiscriminatorValue("developer")
public class Developer extends Employee {
    private String programmingLanguage;
}

Database Table

id
name
departmentName
programmingLanguage
type

1

John

HR

NULL

manager

2

Jane

NULL

Java

developer

Characteristics

Aspect
Details

Performance

Fastest (only one table to join).

Schema

Sparse columns (many NULLs if many subclasses).

Flexibility

Hard to add constraints because unrelated fields exist in same table.

Discriminator

Mandatory (@DiscriminatorColumn).

Example use case

Small inheritance hierarchies with few fields.

2. InheritanceType.TABLE_PER_CLASS

  • Each concrete entity gets its own table.

  • Each table duplicates the columns inherited from parent.

  • No need for discriminator column.

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Employee {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
}
@Entity
public class Manager extends Employee {
    private String departmentName;
}
@Entity
public class Developer extends Employee {
    private String programmingLanguage;
}

Database Tables

Separate table for each subclass. Each table will have own copy of inherited fields.

Manager Table

id
name
departmentName

1

John

HR

3

Bob

Finance

Developer Table

id
name
programmingLanguage

2

Jane

Java

Notes:

  • No NULLs.

  • Duplicate columns (id, name) in all tables.

  • Querying across all employees needs a UNION.

Characteristics

Aspect
Details

Performance

Inserts fast. Queries across hierarchy are slow (UNION needed).

Schema

No NULL fields.

Flexibility

Good if subclasses are quite different.

Discriminator

Not needed.

Example use case

When subclasses are very different and rarely queried together.

3. InheritanceType.JOINED

  • Parent and child classes have their own tables.

  • Tables are linked via primary key / foreign key.

  • Fetching a subclass involves a JOIN.

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Employee {
    @Id
    private Long id;
    private String name;
}
@Entity
public class Manager extends Employee {
    private String departmentName;
}
@Entity
public class Developer extends Employee {
    private String programmingLanguage;
}

Database Tables

One table for base class and one for each subclass. Tables are linked by primary key = foreign key.

Employee Table (base table)

id
name

1

John

2

Jane

3

Bob

Manager Table

id
departmentName

1

HR

3

Finance

Developer Table

id
programmingLanguage

2

Java

Notes:

  • id is Primary Key and Foreign Key in child tables.

  • Fetching a full Manager/Developer record requires JOIN on id.

  • Very normalized.

Characteristics

Aspect
Details

Performance

Slower (needs JOINs on select).

Schema

Normalized (no NULLs).

Flexibility

Best for strict relational modeling.

Discriminator

Optional (can use).

Example use case

When normalized design is required, and JOIN cost is acceptable.

2. @DiscriminatorColumn

About

@DiscriminatorColumn is a JPA annotation used in the context of inheritance mapping in JPA to define a discriminator column. It helps in distinguishing between different entities in the same table when the SINGLE_TABLE or JOINED inheritance strategy is used. This column holds the value that determines which subclass the current row corresponds to.

Why is it Needed?

  • Inheritance Mapping: When using single-table inheritance, all subclasses are stored in the same table. The discriminator column is used to store the type of entity (i.e., the subclass) for each row.

  • Class Differentiation: In databases, there's no direct concept of inheritance, so JPA uses the discriminator column to mark which entity a row belongs to.

  • Performance: The discriminator column avoids using complex joins and makes querying easier and more efficient in the SINGLE_TABLE strategy.

Where is @DiscriminatorColumn Used ?

  • It is used in the parent entity class where inheritance is being mapped.

  • It works in the context of SINGLE_TABLE or JOINED inheritance strategies, where a single table stores all the child entity data (for SINGLE_TABLE) or child entities have their own table but still rely on the base entity table (for JOINED).

Syntax

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "employee_type", discriminatorType = DiscriminatorType.STRING)
public class Employee {
    @Id
    private Long id;
    private String name;
}
  • name: Specifies the name of the discriminator column (e.g., employee_type in the example).

  • discriminatorType: Specifies the type of the discriminator column (STRING, INTEGER, CHAR, etc.). Default is DiscriminatorType.STRING.

How It Works ?

  • The @DiscriminatorColumn defines a special column in the table that stores a discriminator value.

  • The value in this column helps JPA determine which class the row belongs to.

  • @DiscriminatorValue on each subclass specifies the value that will be inserted in the discriminator column for that subclass.

Example Scenario with SINGLE_TABLE Inheritance:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "employee_type", discriminatorType = DiscriminatorType.STRING)
public class Employee {
    @Id
    private Long id;
    private String name;
}

@Entity
@DiscriminatorValue("MANAGER")
public class Manager extends Employee {
    private String departmentName;
}

@Entity
@DiscriminatorValue("DEVELOPER")
public class Developer extends Employee {
    private String programmingLanguage;
}

Database Table Structure (for SINGLE_TABLE strategy):

id
name
employee_type
departmentName
programmingLanguage

1

John

MANAGER

HR

NULL

2

Alice

DEVELOPER

NULL

Java

3

Bob

DEVELOPER

NULL

Python

Key Characteristics

Feature
Details

Purpose

To distinguish between entities when mapped into a single table (or joined strategy).

Discriminator Value

The value in this column helps identify which subclass the row belongs to.

Column Type

Can be STRING, CHAR, INTEGER, etc., depending on the data.

Use Case

Essential for the SINGLE_TABLE inheritance strategy.

Defaults

If not defined, defaults to DTYPE as the column name, and DiscriminatorType.STRING for type.

Inheritance Type

Primarily used in SINGLE_TABLE inheritance, but can also be used in JOINED.

Customizing @DiscriminatorColumn

We can further customize the discriminator column with additional attributes:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name = "employee_type",
    discriminatorType = DiscriminatorType.STRING,
    length = 50, // Set the maximum length of the discriminator value
    columnDefinition = "VARCHAR(50) NOT NULL" // Custom SQL definition for the column
)
public class Employee {
    @Id
    private Long id;
    private String name;
}

Attributes

  • name: Name of the discriminator column.

  • discriminatorType: Type of the discriminator value (can be STRING, INTEGER, etc.).

  • length: Optional. Specifies the maximum length for the discriminator column (default is 31).

  • columnDefinition: Optional. Allows for specifying the column's SQL definition.

When Not to Use @DiscriminatorColumn

  • Performance Concerns: The SINGLE_TABLE strategy may become inefficient when there are a lot of fields that are not relevant for certain subclasses, leading to sparse tables with many NULL values. In such cases, other strategies like JOINED or TABLE_PER_CLASS may be more efficient.

  • Complex Inheritance: If the hierarchy has many deep or unrelated subclasses, managing the @DiscriminatorColumn can become difficult, and you might prefer using a different inheritance strategy.

Best Practices

Best Practice
Details

Keep it Simple

Use SINGLE_TABLE and @DiscriminatorColumn for simple hierarchies. Avoid deep inheritance trees.

Column Type

Use DiscriminatorType.STRING for most cases, but if you need a number, use DiscriminatorType.INTEGER or CHAR for efficiency.

Avoid NULLs

If you are using SINGLE_TABLE strategy, consider the schema design and avoid having many NULL columns for subclasses that don't need them.

Customization

Customize the column definition using columnDefinition if you need more control over how the column is created in the database.

Clear Naming

Ensure clear and meaningful values for the discriminator column values using @DiscriminatorValue.

3. @DiscriminatorValue

About

@DiscriminatorValue is a JPA annotation used to specify the value that will be stored in the discriminator column for each subclass of a parent entity when inheritance is mapped using SINGLE_TABLE or JOINED inheritance strategies. The discriminator column (defined by @DiscriminatorColumn) helps JPA differentiate between different subclasses of the same parent entity in the database.

Why is @DiscriminatorValue Needed?

  • Inheritance Strategy: It is crucial for the SINGLE_TABLE inheritance strategy where all subclasses are stored in the same table. Each subclass needs a discriminator value to tell which entity type the row corresponds to.

  • Entity Type Identification: Without @DiscriminatorValue, JPA cannot distinguish between different types of entities stored in the same table.

  • Efficient Data Storage: Helps in storing and querying different entity types in the same table, which can improve performance and reduce the need for multiple database tables in certain situations.

Where is @DiscriminatorValue Used?

  • It is applied on subclass entities that inherit from a parent entity using a single table inheritance strategy (SINGLE_TABLE or JOINED).

  • Each subclass must declare a value for @DiscriminatorValue that is inserted into the discriminator column when an instance of the subclass is persisted.

Syntax of @DiscriminatorValue

@Entity
@DiscriminatorValue("SUBCLASS_NAME")
public class Subclass extends ParentClass {
    // Class implementation
}
  • @DiscriminatorValue("SUBCLASS_NAME"): Specifies the value that will be stored in the discriminator column for this subclass.

How It Works ?

  • The @DiscriminatorValue annotation is applied to subclasses in the inheritance hierarchy.

  • When an instance of the subclass is saved to the database, JPA inserts the corresponding discriminator value into the discriminator column (defined by @DiscriminatorColumn in the parent entity).

  • JPA uses the value stored in the discriminator column to identify which subclass the row belongs to when querying the data.

Example

Consider a scenario where we have an Employee superclass and two subclasses: Manager and Developer.

Parent Entity

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "employee_type", discriminatorType = DiscriminatorType.STRING)
public class Employee {
    @Id
    private Long id;
    private String name;
    // Getter and Setter methods
}

Subclass 1: Manager

@Entity
@DiscriminatorValue("MANAGER")
public class Manager extends Employee {
    private String departmentName;
    // Getter and Setter methods
}

Subclass 2: Developer

@Entity
@DiscriminatorValue("DEVELOPER")
public class Developer extends Employee {
    private String programmingLanguage;
    // Getter and Setter methods
}

Database Table Structure (for SINGLE_TABLE strategy)

id
name
employee_type
departmentName
programmingLanguage

1

John

MANAGER

HR

NULL

2

Alice

DEVELOPER

NULL

Java

3

Bob

DEVELOPER

NULL

Python

In this case:

  • The employee_type column is the discriminator column.

  • The value "MANAGER" is inserted for the Manager subclass, and "DEVELOPER" for the Developer subclass.

Characteristics of @DiscriminatorValue

Feature
Details

Purpose

Specifies the value that will be stored in the discriminator column for a specific subclass.

Target

Applied to subclasses in an inheritance hierarchy.

Inheritance Strategy

Primarily used in the SINGLE_TABLE inheritance strategy. It can also be used in JOINED.

Discriminator Column

The value is inserted into the column defined by @DiscriminatorColumn.

Value Type

The value can be a string, integer, or other simple types, based on the discriminator column type.

Role

Helps JPA identify which subclass the row in the table represents.

Required

Yes, each subclass in a SINGLE_TABLE inheritance strategy must declare a discriminator value.

Default Behavior of @DiscriminatorValue

If @DiscriminatorValue is not specified on a subclass, JPA will use the class name (converted to a string) as the discriminator value by default.

Example (Implicit Default):

@Entity
@DiscriminatorValue("MANAGER")
public class Manager extends Employee {
    private String departmentName;
}

If @DiscriminatorValue were omitted, the discriminator value for Manager would be automatically set to "Manager", which is the name of the class.

Customizing @DiscriminatorValue

We can customize the discriminator values to make them more readable and relevant to the domain model.

@Entity
@DiscriminatorValue("HR_MANAGER")
public class HRManager extends Manager {
    private String region;
    // Getter and Setter methods
}

In this case, the value "HR_MANAGER" will be used for rows representing HRManager in the discriminator column.

When Not to Use @DiscriminatorValue

  • Complex Relationships: When the inheritance hierarchy involves complex relationships, consider using the JOINED strategy instead, which splits each class into its own table.

  • Multiple Inheritance: If the entity hierarchy is deep with many unrelated subclasses, the SINGLE_TABLE strategy might become inefficient because of the large number of NULL values in the columns.

Previous3. Relationship MappingsNext5. Additional Configuration Annotations

Last updated 1 month ago

Was this helpful?