0
# DataSource Usage
1
2
HikariDataSource is the main entry point for connection pool operations, providing a high-performance implementation of javax.sql.DataSource with automatic connection lifecycle management.
3
4
## Capabilities
5
6
### HikariDataSource Class
7
8
Main DataSource implementation with pooled connection management and lifecycle control.
9
10
```java { .api }
11
/**
12
* The HikariCP pooled DataSource implementation
13
*/
14
public class HikariDataSource extends HikariConfig implements DataSource, Closeable {
15
// Constructors
16
public HikariDataSource();
17
public HikariDataSource(HikariConfig configuration);
18
19
// DataSource interface methods
20
public Connection getConnection() throws SQLException;
21
public Connection getConnection(String username, String password) throws SQLException; // Not supported
22
public PrintWriter getLogWriter() throws SQLException;
23
public void setLogWriter(PrintWriter out) throws SQLException;
24
public void setLoginTimeout(int seconds) throws SQLException;
25
public int getLoginTimeout() throws SQLException;
26
public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException; // Not supported
27
public <T> T unwrap(Class<T> iface) throws SQLException;
28
public boolean isWrapperFor(Class<?> iface) throws SQLException;
29
30
// HikariCP-specific methods
31
public boolean isRunning();
32
public HikariPoolMXBean getHikariPoolMXBean();
33
public HikariConfigMXBean getHikariConfigMXBean();
34
public void evictConnection(Connection connection);
35
public void close();
36
public boolean isClosed();
37
38
// Inherited configuration methods from HikariConfig
39
public void setMetricRegistry(Object metricRegistry);
40
public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory);
41
public void setHealthCheckRegistry(Object healthCheckRegistry);
42
}
43
```
44
45
**Usage Examples:**
46
47
### Basic DataSource Creation and Usage
48
49
```java
50
import com.zaxxer.hikari.HikariConfig;
51
import com.zaxxer.hikari.HikariDataSource;
52
import java.sql.Connection;
53
import java.sql.PreparedStatement;
54
import java.sql.ResultSet;
55
import java.sql.SQLException;
56
57
// Method 1: Using HikariConfig
58
HikariConfig config = new HikariConfig();
59
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
60
config.setUsername("user");
61
config.setPassword("password");
62
config.setMaximumPoolSize(10);
63
64
HikariDataSource dataSource = new HikariDataSource(config);
65
66
// Method 2: Direct configuration (lazy initialization)
67
HikariDataSource dataSource = new HikariDataSource();
68
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
69
dataSource.setUsername("user");
70
dataSource.setPassword("password");
71
dataSource.setMaximumPoolSize(10);
72
73
// Using the DataSource
74
try (Connection connection = dataSource.getConnection()) {
75
try (PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE id = ?")) {
76
stmt.setLong(1, userId);
77
try (ResultSet rs = stmt.executeQuery()) {
78
// Process results
79
}
80
}
81
} catch (SQLException e) {
82
// Handle exceptions
83
}
84
85
// Shutdown when application terminates
86
dataSource.close();
87
```
88
89
### Connection Pool Lifecycle Management
90
91
```java
92
// Check if pool is running
93
if (dataSource.isRunning()) {
94
System.out.println("Pool is active and accepting connections");
95
}
96
97
// Evict a specific connection from the pool
98
Connection connection = dataSource.getConnection();
99
// ... use connection ...
100
dataSource.evictConnection(connection); // Force eviction
101
connection.close(); // Still need to close/return to pool
102
103
// Check if DataSource is closed
104
if (dataSource.isClosed()) {
105
System.out.println("DataSource has been shut down");
106
}
107
108
// Graceful shutdown
109
dataSource.close(); // Closes all connections and shuts down pool
110
```
111
112
### Integration with Connection Pools
113
114
```java
115
// Using try-with-resources for automatic connection management
116
public class DatabaseService {
117
private final HikariDataSource dataSource;
118
119
public DatabaseService() {
120
HikariConfig config = new HikariConfig();
121
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
122
config.setUsername("user");
123
config.setPassword("password");
124
config.setMaximumPoolSize(20);
125
config.setMinimumIdle(5);
126
config.setConnectionTimeout(30000);
127
config.setPoolName("DatabaseService");
128
129
this.dataSource = new HikariDataSource(config);
130
}
131
132
public List<User> findUsers() throws SQLException {
133
List<User> users = new ArrayList<>();
134
135
try (Connection connection = dataSource.getConnection();
136
PreparedStatement stmt = connection.prepareStatement("SELECT id, name, email FROM users");
137
ResultSet rs = stmt.executeQuery()) {
138
139
while (rs.next()) {
140
users.add(new User(
141
rs.getLong("id"),
142
rs.getString("name"),
143
rs.getString("email")
144
));
145
}
146
}
147
148
return users;
149
}
150
151
public void shutdown() {
152
if (dataSource != null && !dataSource.isClosed()) {
153
dataSource.close();
154
}
155
}
156
}
157
```
158
159
### Unwrapping and Wrapper Support
160
161
```java
162
// Check if DataSource wraps a specific type
163
if (dataSource.isWrapperFor(com.mysql.cj.jdbc.MysqlDataSource.class)) {
164
// Unwrap to access underlying DataSource
165
com.mysql.cj.jdbc.MysqlDataSource mysqlDS =
166
dataSource.unwrap(com.mysql.cj.jdbc.MysqlDataSource.class);
167
// Access MySQL-specific features
168
}
169
170
// Unwrap connections for vendor-specific features
171
try (Connection connection = dataSource.getConnection()) {
172
if (connection.isWrapperFor(com.mysql.cj.jdbc.ConnectionImpl.class)) {
173
com.mysql.cj.jdbc.ConnectionImpl mysqlConn =
174
connection.unwrap(com.mysql.cj.jdbc.ConnectionImpl.class);
175
// Use MySQL-specific connection features
176
}
177
}
178
```
179
180
### Error Handling and Connection Recovery
181
182
```java
183
public class RobustDatabaseService {
184
private final HikariDataSource dataSource;
185
186
public void executeQuery() {
187
int maxRetries = 3;
188
int retryCount = 0;
189
190
while (retryCount <= maxRetries) {
191
try (Connection connection = dataSource.getConnection()) {
192
// Execute database operations
193
performDatabaseOperation(connection);
194
break; // Success, exit retry loop
195
196
} catch (SQLException e) {
197
retryCount++;
198
199
if (retryCount > maxRetries) {
200
throw new RuntimeException("Failed after " + maxRetries + " retries", e);
201
}
202
203
// Log and wait before retry
204
System.err.println("Database operation failed, retry " + retryCount + ": " + e.getMessage());
205
206
try {
207
Thread.sleep(1000 * retryCount); // Exponential backoff
208
} catch (InterruptedException ie) {
209
Thread.currentThread().interrupt();
210
throw new RuntimeException("Interrupted during retry", ie);
211
}
212
}
213
}
214
}
215
216
private void performDatabaseOperation(Connection connection) throws SQLException {
217
// Database operations that might fail
218
}
219
}
220
```
221
222
### Spring Framework Integration
223
224
```java
225
@Configuration
226
@EnableTransactionManagement
227
public class DatabaseConfig {
228
229
@Bean(destroyMethod = "close")
230
public DataSource dataSource() {
231
HikariConfig config = new HikariConfig();
232
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
233
config.setUsername("${db.username}");
234
config.setPassword("${db.password}");
235
config.setMaximumPoolSize(20);
236
config.setMinimumIdle(5);
237
config.setConnectionTimeout(30000);
238
config.setPoolName("SpringBootPool");
239
240
return new HikariDataSource(config);
241
}
242
243
@Bean
244
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
245
return new JdbcTemplate(dataSource);
246
}
247
248
@Bean
249
public PlatformTransactionManager transactionManager(DataSource dataSource) {
250
return new DataSourceTransactionManager(dataSource);
251
}
252
}
253
```
254
255
## Connection Management Best Practices
256
257
### Resource Management
258
- Always use try-with-resources for automatic connection cleanup
259
- Close connections promptly to return them to the pool
260
- Never store connections as instance variables
261
262
### Exception Handling
263
- Handle SQLExceptions appropriately
264
- Consider retry logic for transient failures
265
- Use connection eviction for problematic connections
266
267
### Pool Monitoring
268
- Monitor pool statistics through JMX
269
- Set up alerts for connection timeouts
270
- Track connection leak detection events
271
272
### Shutdown Procedures
273
- Always call `dataSource.close()` during application shutdown
274
- Implement graceful shutdown with proper cleanup
275
- Handle shutdown in Spring's destroy methods or shutdown hooks
276
277
## Types
278
279
```java { .api }
280
// Standard JDBC interfaces implemented
281
public interface DataSource extends CommonDataSource, Wrapper {
282
Connection getConnection() throws SQLException;
283
Connection getConnection(String username, String password) throws SQLException;
284
}
285
286
public interface Closeable extends AutoCloseable {
287
void close() throws IOException;
288
}
289
290
// HikariCP-specific interfaces
291
public interface HikariPoolMXBean {
292
int getIdleConnections();
293
int getActiveConnections();
294
int getTotalConnections();
295
int getThreadsAwaitingConnection();
296
void softEvictConnections();
297
void suspendPool();
298
void resumePool();
299
}
300
301
public interface HikariConfigMXBean {
302
// Configuration management interface
303
// (See configuration.md for complete interface)
304
}
305
```