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
  • About
  • Goals of JDBC
  • Features of JDBC
  • 1. Database Connectivity Using Standard Java APIs
  • 2. Execution of SQL Queries and Updates
  • 3. Support for Both Static and Dynamic SQL
  • 4. Transaction Management
  • 5. Exception Handling via SQLException
  • 6. Metadata Access Through DatabaseMetaData and ResultSetMetaData
  • 7. Batch Processing for Performance Optimization
  • 8. Support for Stored Procedures
  • JDBC Architecture
  • 1. JDBC API Layer (Application Layer)
  • 2. JDBC Driver Layer (Communication Layer)
  • Types of JDBC Drivers
  • Type 1: JDBC-ODBC Bridge Driver
  • Type 2: Native-API Driver (Partially Java Driver)
  • Type 3: Network Protocol Driver (Middleware Driver)
  • Type 4: Thin Driver (Pure Java Driver)
  • Comparison
  • JDBC vs ORM (like JPA/Hibernate)

Was this helpful?

  1. Spring
  2. Spring Features
  3. Spring Persistence

JDBC

About

JDBC stands for Java Database Connectivity. It is an API (Application Programming Interface) provided by Java that enables Java applications to interact with databases. JDBC allows Java programs to execute SQL statements, retrieve results, and manage database connections in a standardized way.

It is a part of the Java Standard Edition (Java SE) and acts as a bridge between a Java application and various relational database management systems (RDBMS).

Why JDBC?

Before JDBC, Java applications relied on vendor-specific database APIs which lacked portability. JDBC was introduced by Sun Microsystems (now Oracle) to provide a database-independent interface for Java applications, allowing them to interact with any database that supports JDBC-compliant drivers.

Is JDBC only for SQL? JDBC is primarily designed for relational (SQL) databases, not for NoSQL databases.

JDBC is for SQL-based relational databases such as: MySQL, PostgreSQL, Oracle DB, Microsoft SQL Server, SQLite, DB2, H2, etc.

JDBC is Not Meant for NoSQL databases, such as: MongoDB, Cassandra, Redis, Neo4j, Couchbase, DynamoDB

Can We Use JDBC with NoSQL?

In some cases, Yes, via special JDBC wrappers or drivers provided by vendors.

Examples:

  • MongoDB JDBC Driver – Wraps MongoDB's query interface and exposes it in a JDBC-like way.

  • Cassandra JDBC Driver – Provided by third parties for tools like BI dashboards that require JDBC.

However, these are:

  • Limited in capability

  • Not standardized

  • Often used only to enable JDBC-based tools like Apache Spark, Tableau, or BI reporting tools to read NoSQL data.

Goals of JDBC

  • Provide a standard interface for accessing relational databases.

  • Enable platform-independent database access.

  • Allow developers to execute SQL queries and updates from Java.

  • Support database transactions.

  • Allow metadata retrieval (e.g., information about database structure).

Features of JDBC

1. Database Connectivity Using Standard Java APIs

JDBC provides a standardized interface for Java applications to interact with a wide variety of relational databases. Developers do not need to learn the specific API for each database; instead, they can use the consistent set of JDBC interfaces and classes. This allows applications to remain portable and database-independent, making it easier to switch between databases (e.g., from MySQL to PostgreSQL) with minimal changes in code, provided the appropriate driver is available.

JDBC abstracts the complexity of low-level database communication by offering familiar and consistent object-oriented programming constructs.

2. Execution of SQL Queries and Updates

JDBC enables Java applications to execute SQL commands directly, which include:

  • Queries (SELECT) to retrieve data.

  • Updates (INSERT, UPDATE, DELETE) to modify data.

  • DDL statements (CREATE TABLE, ALTER TABLE, etc.) to manage database structure.

Developers can execute SQL using Statement, PreparedStatement, and CallableStatement interfaces. The results of queries are returned via ResultSet objects, allowing for easy traversal and data extraction.

JDBC gives direct control over SQL execution, enabling the developer to use native SQL features supported by the database.

3. Support for Both Static and Dynamic SQL

  • Static SQL refers to SQL queries that are fixed and hard-coded into the program. These are executed using the Statement interface.

    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
  • Dynamic SQL is generated at runtime and often uses placeholders (?) for parameters. These are supported via PreparedStatement, allowing safer and more flexible query execution.

    PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM employees WHERE department = ?");
    pstmt.setString(1, "HR");

Dynamic SQL makes the application more flexible and secure, particularly in preventing SQL injection attacks.

4. Transaction Management

JDBC provides manual transaction control for managing atomic operations. This is critical for data integrity and consistency. By default, JDBC uses auto-commit mode, where every SQL statement is committed immediately. Developers can disable this and group multiple operations into a single transaction.

conn.setAutoCommit(false);
// Execute multiple queries
conn.commit(); // or conn.rollback();

Transactions ensure that a series of operations either complete entirely or not at all, adhering to the ACID properties of databases.

5. Exception Handling via SQLException

All database-related errors in JDBC are handled using the SQLException class. It provides detailed information such as:

  • Error message

  • SQL state

  • Vendor-specific error code

  • Chained exceptions

Example:

try {
    // JDBC logic
} catch (SQLException e) {
    System.out.println("Error: " + e.getMessage());
}

This structured error handling makes it easier to debug and manage different types of database-related issues programmatically.

6. Metadata Access Through DatabaseMetaData and ResultSetMetaData

JDBC provides access to metadata—data about the database structure and query results:

  • DatabaseMetaData: Used to retrieve information about the database such as table names, supported SQL features, driver details, and more.

  • ResultSetMetaData: Provides details about the columns in a result set, such as column name, type, and size.

Example:

DatabaseMetaData dbMeta = conn.getMetaData();
ResultSetMetaData rsMeta = rs.getMetaData();

Metadata access is useful for building dynamic queries, auto-generating reports, or working with unknown schemas at runtime.

7. Batch Processing for Performance Optimization

JDBC supports batch processing, which allows grouping multiple SQL commands into a single batch and executing them together. This reduces network round-trips and improves performance, especially for operations like inserting large volumes of data.

PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (name) VALUES (?)");
for (String name : nameList) {
    pstmt.setString(1, name);
    pstmt.addBatch();
}
pstmt.executeBatch();

Batch execution can lead to significant performance gains, especially when interacting with large datasets or performing bulk inserts/updates.

8. Support for Stored Procedures

JDBC supports calling stored procedures using the CallableStatement interface. Stored procedures are precompiled SQL routines stored in the database, often used for:

  • Reusability

  • Performance optimization

  • Business logic encapsulation

Example:

CallableStatement cs = conn.prepareCall("{call get_employee_details(?)}");
cs.setInt(1, 101);
ResultSet rs = cs.executeQuery();

Stored procedure support allows complex operations to be offloaded to the database, reducing Java application complexity and improving execution speed.

JDBC Architecture

The JDBC architecture consists of two main layers:

  1. JDBC API Layer (Application Layer)

  2. JDBC Driver Layer (Communication Layer)

1. JDBC API Layer (Application Layer)

This is the upper layer of the JDBC architecture. It is part of the Java Standard Edition API and provides a set of interfaces and classes that Java developers use directly in their applications.

Responsibilities

  • Acts as a bridge between Java applications and the database drivers.

  • Exposes standardized APIs for operations like connecting to databases, executing SQL queries, managing transactions, and processing results.

  • Provides abstraction so developers do not need to worry about database-specific implementations.

Core Interfaces/Classes

  • DriverManager: Loads and manages JDBC drivers. It chooses the appropriate driver for a given database URL.

  • Connection: Represents a session with the database. Used to manage transactions and execute statements.

  • Statement, PreparedStatement, CallableStatement: Used to send SQL commands to the database.

  • ResultSet: Provides access to query results.

  • SQLException: Used for handling errors and exceptions.

  • DatabaseMetaData, ResultSetMetaData: Provide metadata about the database and result sets.

Benefits of JDBC API Layer

  • Database independence: Applications can switch databases without rewriting code.

  • Standardized programming: Developers use a consistent API across all supported databases.

  • Fine-grained control: Gives the programmer control over SQL and JDBC operations.

Example Flow

  1. The application calls DriverManager.getConnection(...).

  2. A Connection object is returned.

  3. The application creates a Statement or PreparedStatement.

  4. SQL queries are sent via this statement.

  5. The results are captured using a ResultSet.

2. JDBC Driver Layer (Communication Layer)

This is the lower layer of the JDBC architecture and contains the actual JDBC driver implementation that communicates directly with the database.

Responsibilities

  • Translates the JDBC API calls into database-specific calls (usually in native code or via protocol).

  • Handles all interactions with the database server, including:

    • Establishing network connections

    • Sending SQL queries

    • Receiving results

    • Handling database errors

How It Works

  • When a JDBC call is made from the application, the call is passed to the DriverManager, which identifies the correct JDBC driver.

  • The driver then translates the JDBC calls into database-native protocol commands.

  • The driver sends these commands to the database and returns the results back to the JDBC API layer.

Benefits of JDBC Driver Layer

  • Database-specific optimizations: Each driver is optimized for the target RDBMS.

  • Decoupling: Java applications don't need to include DB-specific logic.

  • Plug-and-play: Drivers can be swapped to change or upgrade the database backend.

Types of JDBC Drivers

JDBC drivers act as translators between a Java application and the database. They convert Java calls (JDBC API calls) into database-specific calls.

There are four types of JDBC drivers, classified based on how they communicate with the database.

Type 1: JDBC-ODBC Bridge Driver

This driver uses the ODBC (Open Database Connectivity) driver to connect to the database. It translates JDBC method calls into ODBC function calls and relies on a native ODBC driver provided by the database vendor.

Architecture

Java Application → JDBC API → JDBC-ODBC Bridge → ODBC Driver → Database

Requirements

  • odbc32.dll (Windows)

  • ODBC driver installed and configured

Advantages

  • Allows connectivity to any database that supports ODBC.

  • Good for quick prototyping and testing.

Disadvantages

  • Platform-dependent (usually Windows).

  • Slower performance due to multiple layer translations.

  • Not suitable for production.

  • Deprecated since JDK 8 and removed in newer versions.

Use Cases

  • Only suitable for legacy applications or early JDBC experimentation.

Type 2: Native-API Driver (Partially Java Driver)

This driver converts JDBC calls into native C/C++ calls specific to the database API using JNI (Java Native Interface). It requires database vendor-specific native libraries.

Architecture

Java Application → JDBC API → Native-API Driver (JNI) → Native DB Client → Database

Requirements

  • Native database client software must be installed on the client machine.

  • JNI configuration needed.

Advantages

  • Better performance than Type 1.

  • Allows access to proprietary features of the database.

Disadvantages

  • Platform-dependent (native code).

  • Requires extra setup (install native libraries).

  • Harder to deploy and maintain across platforms.

  • Cannot be used in web-based applications easily.

Use Cases

  • Useful when native DB client is already required.

  • Not recommended for enterprise web applications.

Type 3: Network Protocol Driver (Middleware Driver)

This driver uses a middleware server to convert JDBC calls into the database protocol. The Java client communicates with the middleware via a vendor-specific network protocol.

Architecture

Java Application → JDBC API → Type 3 Driver → Middleware Server → Database

Middleware

The middleware component handles:

  • Load balancing

  • Connection pooling

  • Security

  • Data translation

Advantages

  • Platform-independent (no native code).

  • Can connect to multiple databases using a single driver.

  • Good for internet-based applications.

Disadvantages

  • Requires middleware server installation and maintenance.

  • More complex architecture than Type 4.

  • Potential network latency.

Use Cases

  • Suitable for multi-tier enterprise applications.

  • Good for centralized access to different databases.

Type 4: Thin Driver (Pure Java Driver)

This is the most widely used driver. It directly converts JDBC calls into the native protocol of the database, without needing any middleware or native libraries. It is written entirely in Java.

Architecture

Java Application → JDBC API → Type 4 Driver → Database

Examples

  • MySQL: com.mysql.cj.jdbc.Driver

  • PostgreSQL: org.postgresql.Driver

  • Oracle: oracle.jdbc.OracleDriver

Advantages

  • 100% Java, hence platform-independent.

  • Best performance and portability.

  • Easy to deploy—only need the JAR file.

  • Well-supported by modern databases and frameworks.

Disadvantages

  • Each database requires its own Type 4 driver.

  • Vendor-specific optimizations may lead to slight incompatibility.

Use Cases

Recommended for most applications, including: Desktop apps, Web apps, Spring Boot applications, Microservices, Cloud deployments

Comparison

Driver Type
Translation Method
Platform Dependent
Middleware Required
Performance
Usage Today

Type 1

JDBC → ODBC

Yes

No

Low

Deprecated

Type 2

JDBC → Native API

Yes

No

Moderate

Rare

Type 3

JDBC → Middleware → DB

No

Yes

Moderate

Rare

Type 4

JDBC → DB Protocol

No

No

High

Common

JDBC vs ORM (like JPA/Hibernate)

Feature
JDBC
ORM (e.g., JPA/Hibernate)

Mapping

Manual

Automatic

SQL Writing

Required

Optional (auto-generated)

Code Length

Verbose

Concise

Learning Curve

Lower initially

Higher initially

Flexibility

High

Moderate

Abstraction

Low

High

Maintenance

Tedious for large codebases

Easier

PreviousSpring PersistenceNextJDBC Components

Last updated 2 months ago

Was this helpful?