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. @Transient
  • About
  • Why is @Transient Needed?
  • Where is @Transient Used?
  • Syntax of @Transient
  • How It Works
  • JPA @Transient vs Java transient keyword
  • 2. @ElementCollection
  • About
  • Why @ElementCollection is Needed?
  • Where is @ElementCollection Used?
  • How It Works ?
  • Syntax
  • Table Mapping Behind the Scenes
  • Important Supporting Annotations
  • @ElementCollection with @Embeddable
  • How It Is Managed
  • Characteristics of @ElementCollection
  • FetchType in @ElementCollection
  • 3. @Lob
  • About
  • Why @Lob is Needed?
  • Where is @Lob Used?
  • How It Works ?
  • Syntax of @Lob
  • Important Points
  • FetchType Behavior for @Lob
  • Best Practices for @Lob

Was this helpful?

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

5. Additional Configuration Annotations

1. @Transient

About

@Transient is a JPA annotation used to mark a field or property of an entity that should not be persisted (saved) in the database. In other words, JPA ignores this field when reading or writing the entity to the database.

The field will still exist inside the Java object and can be used for temporary, calculated, or helper data — but it will not be mapped to any database column.

Why is @Transient Needed?

  • Temporary Fields: Sometimes you want to maintain a field only for business logic inside your application but don't want it to be stored in the database.

  • Computed Values: You might want a property that is calculated dynamically from other fields and doesn't need database storage.

  • Helper Variables: Fields needed for UI, caching, intermediate results, or computations.

  • DTO Enrichment: When enriching an entity before sending it over the network without affecting database structure.

Without @Transient, JPA would assume that every field should be persisted, leading to errors if no matching database column exists.

Where is @Transient Used?

  • Inside Entity classes (@Entity-annotated classes).

  • On fields or getter methods (depending on whether field access or property access is used).

  • When you have non-persistent data inside an entity.

Syntax of @Transient

@Entity
public class Employee {

    @Id
    private Long id;

    private String name;

    @Transient
    private int calculatedAge; // Not persisted

    // Getter and Setter methods
}

In this example, calculatedAge is present in the Java object but not saved to or retrieved from the database.

Example: @Transient on Getter Method

If we use property-based access (annotations on getters instead of fields):

@Entity
public class Product {

    @Id
    private Long id;

    private String name;

    private double price;

    @Transient
    public double getDiscountedPrice() {
        return price * 0.9; // 10% discount
    }
}

Here, JPA calls the getter when needed but never persists the discounted price.

How It Works

  • During entity persistence (save), JPA ignores the @Transient field.

  • During entity loading (read), JPA does not populate the @Transient field.

  • You are responsible for manually setting or computing the transient field if needed at runtime.

JPA @Transient vs Java transient keyword

Aspect

@Transient (JPA)

transient (Java keyword)

Purpose

Ignore field in database persistence

Ignore field during Java object serialization

Context

JPA/Hibernate ORM mapping

Java Serializable interface

Effect

Field not mapped to a database column

Field not included in a serialized byte stream

Usage

Annotate field with @Transient

Use transient keyword before field declaration

We can even use both together if you want the field to be neither persisted to the database nor serialized to disk.

@Transient
private transient int tempValue;

2. @ElementCollection

About

In JPA, @ElementCollection is used when an entity needs to store a collection of simple types (like String, Integer, etc.) or Embeddable classes, without making them separate entities. Instead of mapping each element to an entity (@Entity), the collection elements are stored in a separate table, automatically managed by JPA.

  • Simple Type Collection → Collection of primitive or basic types (e.g., List<String>).

  • Embeddable Type Collection → Collection of value objects (@Embeddable).

Why @ElementCollection is Needed?

  • When we have multiple simple values associated with a single entity.

  • When we want to avoid creating a full-blown entity for small, dependent data.

  • To keep modelling clean for lightweight data that doesn't need identity (@Id).

Instead of creating separate entities and foreign keys, JPA handles the additional table automatically.

Where is @ElementCollection Used?

  • On fields representing collections (usually List, Set, or Map).

  • Inside an entity class (@Entity).

  • For non-entity elements (simple types or @Embeddable types).

How It Works ?

  • JPA creates a separate table to store the collection elements.

  • It links the records back to the owning entity using a foreign key.

  • The table is managed automatically: insert, update, delete as part of the parent entity's lifecycle.

Syntax

Example: Collection of Basic Types

@Entity
public class Employee {

    @Id
    private Long id;

    private String name;

    @ElementCollection
    @CollectionTable(name = "employee_skills", 
                     joinColumns = @JoinColumn(name = "employee_id"))
    @Column(name = "skill")
    private List<String> skills = new ArrayList<>();

    // Getter and Setter methods
}
  • skills is a list of String.

  • A table called employee_skills will be created with:

    • employee_id (foreign key)

    • skill (the actual skill name)

Table Mapping Behind the Scenes

Employee Table:

id (PK)
name

1

John Doe

Employee_Skills Table:

employee_id (FK)
skill

1

Java

1

Spring Boot

1

Hibernate

Important Supporting Annotations

Annotation
Purpose

@CollectionTable

Defines the table name and join columns for the collection.

@Column

Defines the name of the column that stores the element value itself.

If we don't specify @CollectionTable, JPA automatically generates a table name and foreign key.

@ElementCollection with @Embeddable

We can also store complex value objects instead of just simple types.

@Embeddable
public class Address {
    private String street;
    private String city;
    private String zipCode;
    // Getter and Setter
}
@Entity
public class Customer {

    @Id
    private Long id;

    private String name;

    @ElementCollection
    @CollectionTable(name = "customer_addresses", 
                     joinColumns = @JoinColumn(name = "customer_id"))
    private List<Address> addresses = new ArrayList<>();

    // Getter and Setter methods
}

Here:

  • A customer_addresses table will be created.

  • It will have columns for customer_id, street, city, zipCode.

How It Is Managed

  • Insertion: When we save the parent entity, the collection elements are inserted automatically.

  • Deletion: When we delete or update, the corresponding collection records are handled automatically.

  • No Separate Identity: Elements are part of the parent entity, they are not independent entities.

Characteristics of @ElementCollection

Aspect
Details

Purpose

To map collections of simple types or embeddable types.

Database Behavior

A separate table is created automatically to store the collection elements.

Lifecycle

Tied to the parent entity’s lifecycle.

Identity

Elements have no primary key; the parent's foreign key manages the relationship.

Fetching

Default is LAZY fetching (loaded only when accessed).

Operations

Insert, update, delete are cascaded from the owning entity automatically.

FetchType in @ElementCollection

  • By default, FetchType.LAZY is applied.

  • We can manually make it FetchType.EAGER if you want the collection to load immediately.

@ElementCollection(fetch = FetchType.EAGER)
private List<String> skills;

Use EAGER cautiously — it might lead to performance overhead if the collection is large.

3. @Lob

About

  • In JPA, @Lob is used to map large objects to database columns.

  • It marks a persistent property or field to be stored as either:

    • BLOB (Binary Large Object) → for binary data like images, files, etc.

    • CLOB (Character Large Object) → for large text content.

JPA automatically decides whether to use a BLOB or CLOB based on the Java type.

Why @Lob is Needed?

  • To store large amounts of data (binary or text) in the database without size limitations of standard columns.

  • To map fields like:

    • Long textual content (articles, descriptions, logs).

    • Large files (images, videos, PDFs, audio, etc.).

Where is @Lob Used?

  • On entity fields of type:

    • String (for large text → CLOB)

    • byte[] (for binary data → BLOB)

    • Serializable objects (if using Java object serialization)

  • Inside a class annotated with @Entity.

How It Works ?

  • If the field type is String, JPA maps it as a CLOB.

  • If the field type is byte[], JPA maps it as a BLOB.

  • The corresponding database column is treated as large object storage.

Syntax of @Lob

Example: Storing Large Text (CLOB)

@Entity
public class Article {

    @Id
    private Long id;

    private String title;

    @Lob
    @Column(name = "content", columnDefinition = "CLOB")
    private String content;

    // Getter and Setter
}
  • content is a large text field.

  • It will be stored as a CLOB in the database.

Example: Storing Binary Data (BLOB)

@Entity
public class Document {

    @Id
    private Long id;

    private String name;

    @Lob
    @Column(name = "file_data", columnDefinition = "BLOB")
    private byte[] fileData;

    // Getter and Setter
}
  • fileData is a byte array.

  • It will be stored as a BLOB in the database.

Example: Serializable Object

We can serialize Java objects into a BLOB.

@Entity
public class Report {

    @Id
    private Long id;

    private String title;

    @Lob
    private Serializable reportData;

    // Getter and Setter
}
  • reportData must be a Serializable object.

  • Stored as a serialized byte stream in the database.

Important Points

  • CLOB: Large character/text storage — Used for things like articles, logs, documentation.

  • BLOB: Large binary storage — Used for things like images, files, attachments.

  • Lazy Fetching: LOB fields are usually fetched lazily (FetchType.LAZY) by JPA providers to avoid memory overload.

  • Size Limitation: BLOB/CLOB allows storing very large amounts of data, beyond the limit of VARCHAR or similar standard types.

  • Database Support: Actual behavior can vary slightly depending on the database (Oracle, MySQL, PostgreSQL, etc.).

FetchType Behavior for @Lob

  • According to the JPA specification, @Lob annotated fields are recommended to be lazily fetched.

  • But, it depends on the provider (Hibernate, EclipseLink, etc.).

  • We can explicitly specify:

@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] image;

Best Practices for @Lob

Best Practice
Details

Use Lazy Fetching

To avoid loading large data when not needed.

Separate Large Data

If possible, keep LOB data in a separate table to avoid heavy load during regular queries.

Explicit Column Types

Use @Column(columnDefinition = "CLOB" or "BLOB") if you want to tightly control DDL generation.

Optimize Database Storage

Ensure database tablespace is designed to handle large LOBs properly.

Handle Streams

If LOB data is very large, prefer streaming APIs instead of loading everything into memory at once.

Previous4. Inheritance MappingsNextQuerying Data

Last updated 1 month ago

Was this helpful?