0
# Data Access & Persistence
1
2
Database connectivity, transaction management, and ORM integration with support for JDBC, JPA, R2DBC, and database migration tools.
3
4
## Capabilities
5
6
### JDBC Support
7
8
Core JDBC utilities and data source management.
9
10
```java { .api }
11
/**
12
* Convenience class for building a DataSource
13
*/
14
public final class DataSourceBuilder {
15
/**
16
* Get a DataSourceBuilder
17
* @return a new data source builder instance
18
*/
19
public static DataSourceBuilder create();
20
21
/**
22
* Get a DataSourceBuilder based on the specified class loader
23
* @param classLoader the class loader used to create the builder
24
* @return a new data source builder instance
25
*/
26
public static DataSourceBuilder create(ClassLoader classLoader);
27
28
/**
29
* Return a new builder based on the state of this builder but with the specified type used for the DataSource
30
* @param type the DataSource type
31
* @return a new builder
32
*/
33
public DataSourceBuilder type(Class<? extends DataSource> type);
34
35
/**
36
* Return a new builder based on the state of this builder but with the specified URL
37
* @param url the JDBC URL
38
* @return a new builder
39
*/
40
public DataSourceBuilder url(String url);
41
42
/**
43
* Return a new builder based on the state of this builder but with the specified username
44
* @param username the username
45
* @return a new builder
46
*/
47
public DataSourceBuilder username(String username);
48
49
/**
50
* Return a new builder based on the state of this builder but with the specified password
51
* @param password the password
52
* @return a new builder
53
*/
54
public DataSourceBuilder password(String password);
55
56
/**
57
* Return a new builder based on the state of this builder but with the specified driver class name
58
* @param driverClassName the driver class name
59
* @return a new builder
60
*/
61
public DataSourceBuilder driverClassName(String driverClassName);
62
63
/**
64
* Build a DataSource with the current state of this builder
65
* @return a DataSource
66
*/
67
public <T extends DataSource> T build();
68
}
69
70
/**
71
* Common database drivers used by Spring Boot
72
*/
73
public enum DatabaseDriver {
74
/**
75
* Apache Derby database driver
76
*/
77
DERBY("org.apache.derby.jdbc.EmbeddedDriver", "org.apache.derby.jdbc.EmbeddedXADataSource"),
78
79
/**
80
* H2 database driver
81
*/
82
H2("org.h2.Driver", "org.h2.jdbcx.JdbcDataSource"),
83
84
/**
85
* HyperSQL database driver
86
*/
87
HSQLDB("org.hsqldb.jdbc.JDBCDriver", "org.hsqldb.jdbc.pool.JDBCXADataSource"),
88
89
/**
90
* SQLite database driver
91
*/
92
SQLITE("org.sqlite.JDBC"),
93
94
/**
95
* MySQL database driver
96
*/
97
MYSQL("com.mysql.cj.jdbc.Driver", "com.mysql.cj.jdbc.MysqlXADataSource", "jdbc:mysql:"),
98
99
/**
100
* MariaDB database driver
101
*/
102
MARIADB("org.mariadb.jdbc.Driver", "org.mariadb.jdbc.MariaDbDataSource", "jdbc:mariadb:"),
103
104
/**
105
* PostgreSQL database driver
106
*/
107
POSTGRESQL("org.postgresql.Driver", "org.postgresql.xa.PGXADataSource", "jdbc:postgresql:"),
108
109
/**
110
* Oracle database driver
111
*/
112
ORACLE("oracle.jdbc.OracleDriver", "oracle.jdbc.xa.client.OracleXADataSource", "jdbc:oracle:"),
113
114
/**
115
* Microsoft SQL Server database driver
116
*/
117
SQLSERVER("com.microsoft.sqlserver.jdbc.SQLServerDriver",
118
"com.microsoft.sqlserver.jdbc.SQLServerXADataSource", "jdbc:sqlserver:");
119
120
private final String driverClassName;
121
private final String xaDataSourceClassName;
122
private final String urlPrefix;
123
124
/**
125
* Return the driver class name
126
* @return the driver class name
127
*/
128
public String getDriverClassName();
129
130
/**
131
* Return the XA DataSource class name
132
* @return the XA DataSource class name
133
*/
134
public String getXaDataSourceClassName();
135
136
/**
137
* Return the URL prefix for this driver
138
* @return the URL prefix
139
*/
140
public String getUrlPrefix();
141
142
/**
143
* Find a DatabaseDriver for the given URL
144
* @param url the JDBC URL
145
* @return the database driver or null
146
*/
147
public static DatabaseDriver fromJdbcUrl(String url);
148
149
/**
150
* Find a DatabaseDriver for the given driver class name
151
* @param driverClassName the driver class name
152
* @return the database driver or null
153
*/
154
public static DatabaseDriver fromDriverClassName(String driverClassName);
155
}
156
157
/**
158
* Connection details for embedded databases
159
*/
160
public enum EmbeddedDatabaseConnection {
161
/**
162
* No embedded database
163
*/
164
NONE(null, null, null),
165
166
/**
167
* H2 embedded database connection
168
*/
169
H2(DatabaseDriver.H2, "org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration$H2EmbeddedConfiguration",
170
"jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"),
171
172
/**
173
* Derby embedded database connection
174
*/
175
DERBY(DatabaseDriver.DERBY, "org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration$DerbyEmbeddedConfiguration",
176
"jdbc:derby:memory:%s;create=true"),
177
178
/**
179
* HSQL embedded database connection
180
*/
181
HSQLDB(DatabaseDriver.HSQLDB, "org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration$HsqldbEmbeddedConfiguration",
182
"jdbc:hsqldb:mem:%s");
183
184
private final DatabaseDriver databaseDriver;
185
private final String type;
186
private final String url;
187
188
/**
189
* Returns the driver class for the embedded database
190
* @return the driver class
191
*/
192
public String getDriverClassName();
193
194
/**
195
* Returns the URL for the embedded database
196
* @param databaseName the database name
197
* @return the database URL
198
*/
199
public String getUrl(String databaseName);
200
201
/**
202
* Convenience method to determine if a driver class corresponds to this connection
203
* @param driverClass the driver class
204
* @return true if the driver class matches
205
*/
206
public boolean isDriverClass(String driverClass);
207
208
/**
209
* Get the EmbeddedDatabaseConnection for the given class loader
210
* @param classLoader the class loader used to check for classes
211
* @return the embedded connection
212
*/
213
public static EmbeddedDatabaseConnection get(ClassLoader classLoader);
214
}
215
```
216
217
**Usage Examples:**
218
219
```java
220
// Basic DataSource configuration
221
@Configuration
222
public class DatabaseConfig {
223
224
@Bean
225
@ConfigurationProperties(prefix = "app.datasource")
226
public DataSource dataSource() {
227
return DataSourceBuilder.create()
228
.type(HikariDataSource.class)
229
.build();
230
}
231
}
232
233
// Multiple DataSource configuration
234
@Configuration
235
public class MultipleDataSourceConfig {
236
237
@Bean
238
@Primary
239
@ConfigurationProperties(prefix = "app.datasource.primary")
240
public DataSource primaryDataSource() {
241
return DataSourceBuilder.create().build();
242
}
243
244
@Bean
245
@ConfigurationProperties(prefix = "app.datasource.secondary")
246
public DataSource secondaryDataSource() {
247
return DataSourceBuilder.create().build();
248
}
249
}
250
```
251
252
### JPA & ORM Support
253
254
Java Persistence API and Object-Relational Mapping support.
255
256
```java { .api }
257
/**
258
* Configures the base packages used by auto-configuration when scanning for entity classes
259
*/
260
@Target(ElementType.TYPE)
261
@Retention(RetentionPolicy.RUNTIME)
262
@interface EntityScan {
263
/**
264
* Alias for basePackages()
265
* @return the base packages to scan
266
*/
267
String[] value() default {};
268
269
/**
270
* Base packages to scan for entities
271
* @return the base packages to scan
272
*/
273
String[] basePackages() default {};
274
275
/**
276
* Type-safe alternative to basePackages() for specifying packages to scan for entities
277
* @return the base package classes
278
*/
279
Class<?>[] basePackageClasses() default {};
280
}
281
282
/**
283
* Callback interface that can be used to customize Hibernate properties
284
*/
285
@FunctionalInterface
286
public interface HibernatePropertiesCustomizer {
287
/**
288
* Customize the specified Hibernate properties
289
* @param hibernateProperties the hibernate properties to customize
290
*/
291
void customize(Map<String, Object> hibernateProperties);
292
}
293
294
/**
295
* Callback interface that can be used to customize JPA properties
296
*/
297
@FunctionalInterface
298
public interface JpaPropertiesCustomizer {
299
/**
300
* Customize the specified JPA properties
301
* @param jpaProperties the JPA properties to customize
302
*/
303
void customize(Map<String, Object> jpaProperties);
304
}
305
```
306
307
**Usage Examples:**
308
309
```java
310
// Entity scanning configuration
311
@SpringBootApplication
312
@EntityScan(basePackages = {"com.example.entities", "com.example.domain"})
313
public class Application {
314
public static void main(String[] args) {
315
SpringApplication.run(Application.class, args);
316
}
317
}
318
319
// Custom Hibernate properties
320
@Configuration
321
public class HibernateConfig {
322
323
@Bean
324
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer() {
325
return properties -> {
326
properties.put("hibernate.show_sql", true);
327
properties.put("hibernate.format_sql", true);
328
properties.put("hibernate.use_sql_comments", true);
329
properties.put("hibernate.jdbc.batch_size", 20);
330
};
331
}
332
}
333
334
// JPA repository configuration
335
@EnableJpaRepositories(basePackages = "com.example.repositories")
336
@Configuration
337
public class JpaConfig {
338
339
@Bean
340
public JpaPropertiesCustomizer jpaPropertiesCustomizer() {
341
return properties -> {
342
properties.put("javax.persistence.validation.mode", "callback");
343
properties.put("javax.persistence.schema-generation.database.action", "validate");
344
};
345
}
346
}
347
```
348
349
### R2DBC Support
350
351
Reactive Relational Database Connectivity for non-blocking database access.
352
353
```java { .api }
354
/**
355
* Builder for creating R2DBC ConnectionFactory instances
356
*/
357
public final class ConnectionFactoryBuilder {
358
/**
359
* Create a new ConnectionFactoryBuilder
360
* @return a new connection factory builder
361
*/
362
public static ConnectionFactoryBuilder create();
363
364
/**
365
* Configure the connection factory URL
366
* @param url the connection URL
367
* @return the builder
368
*/
369
public ConnectionFactoryBuilder url(String url);
370
371
/**
372
* Configure the driver class name
373
* @param driver the driver class name
374
* @return the builder
375
*/
376
public ConnectionFactoryBuilder driver(String driver);
377
378
/**
379
* Configure the connection host
380
* @param host the host
381
* @return the builder
382
*/
383
public ConnectionFactoryBuilder host(String host);
384
385
/**
386
* Configure the connection port
387
* @param port the port
388
* @return the builder
389
*/
390
public ConnectionFactoryBuilder port(int port);
391
392
/**
393
* Configure the database name
394
* @param database the database name
395
* @return the builder
396
*/
397
public ConnectionFactoryBuilder database(String database);
398
399
/**
400
* Configure the username
401
* @param username the username
402
* @return the builder
403
*/
404
public ConnectionFactoryBuilder username(String username);
405
406
/**
407
* Configure the password
408
* @param password the password
409
* @return the builder
410
*/
411
public ConnectionFactoryBuilder password(String password);
412
413
/**
414
* Configure an option
415
* @param option the option name
416
* @param value the option value
417
* @return the builder
418
*/
419
public ConnectionFactoryBuilder option(String option, Object value);
420
421
/**
422
* Build the ConnectionFactory
423
* @return the connection factory
424
*/
425
public ConnectionFactory build();
426
}
427
428
/**
429
* Script-based DataBaseInitializer for R2DBC
430
*/
431
public class R2dbcScriptDatabaseInitializer extends AbstractScriptDatabaseInitializer {
432
/**
433
* Create a new R2dbcScriptDatabaseInitializer instance
434
* @param connectionFactory the connection factory to use
435
* @param settings the initialization settings
436
*/
437
public R2dbcScriptDatabaseInitializer(ConnectionFactory connectionFactory, DatabaseInitializationSettings settings);
438
439
@Override
440
protected boolean supportsDatabase(DatabaseDriver driver);
441
}
442
```
443
444
**Usage Examples:**
445
446
```java
447
// R2DBC ConnectionFactory configuration
448
@Configuration
449
@EnableR2dbcRepositories
450
public class R2dbcConfig {
451
452
@Bean
453
@ConfigurationProperties(prefix = "app.r2dbc")
454
public ConnectionFactory connectionFactory() {
455
return ConnectionFactoryBuilder.create()
456
.driver("postgresql")
457
.host("localhost")
458
.port(5432)
459
.database("testdb")
460
.username("user")
461
.password("password")
462
.build();
463
}
464
465
@Bean
466
public R2dbcTransactionManager transactionManager(ConnectionFactory connectionFactory) {
467
return new R2dbcTransactionManager(connectionFactory);
468
}
469
}
470
```
471
472
### Database Migration
473
474
Database migration tools integration for Flyway and Liquibase.
475
476
```java { .api }
477
/**
478
* Strategy interface used to determine how Flyway migration should be applied
479
*/
480
@FunctionalInterface
481
public interface FlywayMigrationStrategy {
482
/**
483
* Trigger flyway migration
484
* @param flyway the flyway instance
485
*/
486
void migrate(Flyway flyway);
487
}
488
489
/**
490
* Strategy interface used to determine how Liquibase migration should be applied
491
*/
492
@FunctionalInterface
493
public interface LiquibaseMigrationStrategy {
494
/**
495
* Trigger liquibase migration
496
* @param liquibase the liquibase instance
497
*/
498
void migrate(Liquibase liquibase);
499
}
500
501
/**
502
* Callback interface that can be used to customize Flyway configuration
503
*/
504
@FunctionalInterface
505
public interface FlywayConfigurationCustomizer {
506
/**
507
* Customize the given Flyway configuration
508
* @param configuration the configuration to customize
509
*/
510
void customize(FluentConfiguration configuration);
511
}
512
```
513
514
**Usage Examples:**
515
516
```java
517
// Custom Flyway migration strategy
518
@Configuration
519
public class MigrationConfig {
520
521
@Bean
522
public FlywayMigrationStrategy flywayMigrationStrategy() {
523
return flyway -> {
524
// Clean the database first (only for development!)
525
if (isDevelopmentEnvironment()) {
526
flyway.clean();
527
}
528
flyway.migrate();
529
};
530
}
531
532
@Bean
533
public FlywayConfigurationCustomizer flywayConfigurationCustomizer() {
534
return configuration -> {
535
configuration
536
.locations("classpath:db/migration", "classpath:db/data")
537
.placeholders(Map.of("engine", "InnoDB"))
538
.validateOnMigrate(true);
539
};
540
}
541
}
542
543
// Custom Liquibase migration strategy
544
@Configuration
545
public class LiquibaseConfig {
546
547
@Bean
548
public LiquibaseMigrationStrategy liquibaseMigrationStrategy() {
549
return liquibase -> {
550
try {
551
liquibase.update("production");
552
} catch (Exception e) {
553
throw new RuntimeException("Failed to migrate database", e);
554
}
555
};
556
}
557
}
558
```
559
560
### Database Initialization
561
562
Database initialization support for SQL scripts and schema creation.
563
564
```java { .api }
565
/**
566
* Settings for initializing a SQL database
567
*/
568
public class DatabaseInitializationSettings {
569
/**
570
* Create new database initialization settings
571
*/
572
public DatabaseInitializationSettings();
573
574
/**
575
* Set the schema locations
576
* @param schemaLocations the schema locations
577
*/
578
public void setSchemaLocations(List<String> schemaLocations);
579
580
/**
581
* Get the schema locations
582
* @return the schema locations
583
*/
584
public List<String> getSchemaLocations();
585
586
/**
587
* Set the data locations
588
* @param dataLocations the data locations
589
*/
590
public void setDataLocations(List<String> dataLocations);
591
592
/**
593
* Get the data locations
594
* @return the data locations
595
*/
596
public List<String> getDataLocations();
597
598
/**
599
* Set whether to continue on error
600
* @param continueOnError whether to continue on error
601
*/
602
public void setContinueOnError(boolean continueOnError);
603
604
/**
605
* Get whether to continue on error
606
* @return whether to continue on error
607
*/
608
public boolean isContinueOnError();
609
610
/**
611
* Set the statement separator
612
* @param separator the statement separator
613
*/
614
public void setSeparator(String separator);
615
616
/**
617
* Get the statement separator
618
* @return the statement separator
619
*/
620
public String getSeparator();
621
622
/**
623
* Set the SQL script encoding
624
* @param encoding the encoding
625
*/
626
public void setEncoding(Charset encoding);
627
628
/**
629
* Get the SQL script encoding
630
* @return the encoding
631
*/
632
public Charset getEncoding();
633
}
634
635
/**
636
* Base class for script-based database initializers
637
*/
638
public abstract class AbstractScriptDatabaseInitializer implements DatabaseInitializer {
639
/**
640
* Create a new AbstractScriptDatabaseInitializer
641
* @param settings the initialization settings
642
*/
643
protected AbstractScriptDatabaseInitializer(DatabaseInitializationSettings settings);
644
645
@Override
646
public boolean initializeDatabase();
647
648
/**
649
* Returns whether the given database driver is supported
650
* @param driver the database driver
651
* @return true if supported
652
*/
653
protected abstract boolean supportsDatabase(DatabaseDriver driver);
654
}
655
```