Spring JDBC abstraction and DAO support providing template-based database access and comprehensive transaction management
npx @tessl/cli install tessl/maven-org-springframework--spring-jdbc@6.2.00
# Spring JDBC
1
2
Spring JDBC provides a comprehensive abstraction layer over raw JDBC operations, eliminating boilerplate code while maintaining full control over SQL execution. It offers multiple programming models from low-level template-based access to modern fluent APIs, with sophisticated exception translation, transaction management, and DataSource support.
3
4
## Package Information
5
6
- **Package Name**: org.springframework:spring-jdbc
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**: Add to Maven dependencies:
10
```xml
11
<dependency>
12
<groupId>org.springframework</groupId>
13
<artifactId>spring-jdbc</artifactId>
14
<version>6.2.8</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
import org.springframework.jdbc.core.JdbcTemplate;
22
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
23
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
24
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
25
import org.springframework.jdbc.core.simple.JdbcClient;
26
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
27
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
28
import org.springframework.jdbc.core.RowMapper;
29
import org.springframework.jdbc.core.ResultSetExtractor;
30
import org.springframework.jdbc.core.PreparedStatementCallback;
31
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
32
import org.springframework.jdbc.support.KeyHolder;
33
import javax.sql.DataSource;
34
```
35
36
## Basic Usage
37
38
```java
39
import org.springframework.jdbc.core.JdbcTemplate;
40
import org.springframework.jdbc.core.RowMapper;
41
import javax.sql.DataSource;
42
43
// Basic template usage
44
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
45
46
// Simple query
47
String name = jdbcTemplate.queryForObject(
48
"SELECT name FROM users WHERE id = ?",
49
String.class,
50
userId
51
);
52
53
// Query with row mapper
54
List<User> users = jdbcTemplate.query(
55
"SELECT id, name, email FROM users WHERE active = ?",
56
(rs, rowNum) -> new User(
57
rs.getLong("id"),
58
rs.getString("name"),
59
rs.getString("email")
60
),
61
true
62
);
63
64
// Update operation
65
int rowsAffected = jdbcTemplate.update(
66
"UPDATE users SET last_login = ? WHERE id = ?",
67
Timestamp.from(Instant.now()),
68
userId
69
);
70
```
71
72
## Architecture
73
74
Spring JDBC is built around several key architectural patterns:
75
76
- **Template Method Pattern**: `JdbcTemplate` and related classes handle resource management, connection handling, and exception translation while delegating specific operations to callback interfaces
77
- **Callback Pattern**: Extensive use of functional interfaces (`RowMapper`, `ResultSetExtractor`, `PreparedStatementCallback`) for custom behavior injection
78
- **Strategy Pattern**: Pluggable exception translation, row mapping strategies, and DataSource lookup mechanisms
79
- **Factory Pattern**: Statement creators, metadata providers, and DataSource factories for flexible object creation
80
- **Proxy Pattern**: DataSource proxies for transaction awareness, connection pooling, and resource management
81
82
The framework eliminates JDBC boilerplate while providing fine-grained control over SQL execution, automatic resource cleanup, and comprehensive error handling through Spring's DataAccessException hierarchy.
83
84
## Capabilities
85
86
### Core Template Operations
87
88
Template-based JDBC operations providing the foundation for database access. Handles resource management, exception translation, and provides multiple query/update methods.
89
90
```java { .api }
91
public class JdbcTemplate implements JdbcOperations {
92
public JdbcTemplate(DataSource dataSource);
93
94
// Query operations
95
public <T> T queryForObject(String sql, Class<T> requiredType, Object... args);
96
public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args);
97
public List<Map<String, Object>> queryForList(String sql, Object... args);
98
99
// Update operations
100
public int update(String sql, Object... args);
101
public int[] batchUpdate(String sql, List<Object[]> batchArgs);
102
}
103
```
104
105
[Core Template Operations](./core-template.md)
106
107
### Named Parameter Operations
108
109
Named parameter support for more readable and maintainable SQL with parameter binding using Maps and SqlParameterSource implementations.
110
111
```java { .api }
112
public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations {
113
public NamedParameterJdbcTemplate(DataSource dataSource);
114
115
public <T> T queryForObject(String sql, SqlParameterSource paramSource, Class<T> requiredType);
116
public <T> List<T> query(String sql, Map<String, ?> paramMap, RowMapper<T> rowMapper);
117
public int update(String sql, SqlParameterSource paramSource);
118
}
119
120
public class MapSqlParameterSource extends AbstractSqlParameterSource {
121
public MapSqlParameterSource addValue(String paramName, Object value);
122
public MapSqlParameterSource addValues(Map<String, ?> values);
123
}
124
```
125
126
[Named Parameter Operations](./named-parameter.md)
127
128
### Modern Fluent Client
129
130
Modern fluent API introduced in Spring 6.1 providing a unified facade for JDBC operations with method chaining and type-safe parameter binding.
131
132
```java { .api }
133
public interface JdbcClient {
134
static JdbcClient create(DataSource dataSource);
135
136
StatementSpec sql(String sql);
137
138
interface StatementSpec {
139
StatementSpec param(Object value);
140
StatementSpec params(Object... values);
141
<T> MappedQuerySpec<T> query(Class<T> mappedClass);
142
UpdateSpec update();
143
}
144
}
145
```
146
147
[Modern Fluent Client](./fluent-client.md)
148
149
### Simple Operations
150
151
Simplified operations for common database tasks including inserts with key generation and stored procedure calls with minimal configuration.
152
153
```java { .api }
154
public class SimpleJdbcInsert implements SimpleJdbcInsertOperations {
155
public SimpleJdbcInsert(DataSource dataSource);
156
public SimpleJdbcInsert withTableName(String tableName);
157
public SimpleJdbcInsert usingGeneratedKeyColumns(String... columnNames);
158
public Number executeAndReturnKey(Map<String, ?> args);
159
}
160
161
public class SimpleJdbcCall implements SimpleJdbcCallOperations {
162
public SimpleJdbcCall(DataSource dataSource);
163
public SimpleJdbcCall withProcedureName(String procedureName);
164
public Map<String, Object> execute(Map<String, ?> inParams);
165
}
166
```
167
168
[Simple Operations](./simple-operations.md)
169
170
### DataSource Management
171
172
Comprehensive DataSource implementations and utilities for connection management, including embedded databases, connection pooling, and transaction-aware proxies.
173
174
```java { .api }
175
public class DriverManagerDataSource extends AbstractDriverBasedDataSource {
176
public void setUrl(String url);
177
public void setUsername(String username);
178
public void setPassword(String password);
179
}
180
181
public class EmbeddedDatabaseBuilder {
182
public EmbeddedDatabaseBuilder setType(EmbeddedDatabaseType type);
183
public EmbeddedDatabaseBuilder addScript(String script);
184
public EmbeddedDatabase build();
185
}
186
```
187
188
[DataSource Management](./datasource-management.md)
189
190
### Transaction Management
191
192
Declarative and programmatic transaction support with integration into Spring's transaction management infrastructure.
193
194
```java { .api }
195
public class DataSourceTransactionManager extends AbstractPlatformTransactionManager {
196
public DataSourceTransactionManager(DataSource dataSource);
197
public void setEnforceReadOnly(boolean enforceReadOnly);
198
}
199
200
public abstract class DataSourceUtils {
201
public static Connection getConnection(DataSource dataSource);
202
public static void releaseConnection(Connection con, DataSource dataSource);
203
}
204
```
205
206
[Transaction Management](./transaction-management.md)
207
208
### Exception Handling and Utilities
209
210
Exception translation from SQLException to Spring's DataAccessException hierarchy, plus utility classes for JDBC operations and metadata access.
211
212
```java { .api }
213
public interface SQLExceptionTranslator {
214
DataAccessException translate(String task, String sql, SQLException ex);
215
}
216
217
public abstract class JdbcUtils {
218
public static void closeConnection(Connection con);
219
public static void closeStatement(Statement stmt);
220
public static Object getResultSetValue(ResultSet rs, int index);
221
}
222
```
223
224
[Exception Handling and Utilities](./exception-handling.md)
225
226
## Types
227
228
```java { .api }
229
// Core callback interfaces
230
@FunctionalInterface
231
public interface RowMapper<T> {
232
T mapRow(ResultSet rs, int rowNum) throws SQLException;
233
}
234
235
@FunctionalInterface
236
public interface ResultSetExtractor<T> {
237
T extractData(ResultSet rs) throws SQLException, DataAccessException;
238
}
239
240
@FunctionalInterface
241
public interface PreparedStatementCallback<T> {
242
T doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException;
243
}
244
245
// Parameter binding
246
public interface SqlParameterSource {
247
boolean hasValue(String paramName);
248
Object getValue(String paramName) throws IllegalArgumentException;
249
int getSqlType(String paramName);
250
}
251
252
// Key generation support
253
public interface KeyHolder {
254
Number getKey() throws InvalidDataAccessApiUsageException;
255
Map<String, Object> getKeys() throws InvalidDataAccessApiUsageException;
256
List<Map<String, Object>> getKeyList();
257
}
258
```