0
# Data Configuration
1
2
Spring Boot's data configuration provides comprehensive auto-configuration for data access technologies including relational databases, NoSQL systems, JPA/Hibernate, Spring Data repositories, and connection pooling.
3
4
## Capabilities
5
6
### DataSource Configuration
7
8
Auto-configuration for database connections and connection pooling.
9
10
```java { .api }
11
/**
12
* Auto-configuration for DataSource
13
* Provides automatic configuration of database connections with connection pooling
14
*/
15
@AutoConfiguration
16
@ConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})
17
@ConditionalOnMissingBean(type = "io.r2dbc.spi.ConnectionFactory")
18
@EnableConfigurationProperties(DataSourceProperties.class)
19
public class DataSourceAutoConfiguration {
20
21
/**
22
* Configuration for embedded databases (H2, HSQL, Derby)
23
*/
24
@Configuration(proxyBeanMethods = false)
25
@Conditional(EmbeddedDatabaseCondition.class)
26
@ConditionalOnMissingBean({DataSource.class, XADataSource.class})
27
@Import(EmbeddedDataSourceConfiguration.class)
28
protected static class EmbeddedDatabaseConfiguration {
29
}
30
31
/**
32
* Configuration for pooled data sources
33
*/
34
@Configuration(proxyBeanMethods = false)
35
@ConditionalOnMissingBean({DataSource.class, XADataSource.class})
36
@ConditionalOnProperty(name = "spring.datasource.type")
37
static class Generic {
38
39
@Bean
40
DataSource dataSource(DataSourceProperties properties) {
41
return properties.initializeDataSourceBuilder().build();
42
}
43
}
44
45
/**
46
* Configuration for HikariCP connection pool (default)
47
*/
48
@Configuration(proxyBeanMethods = false)
49
@ConditionalOnClass(HikariDataSource.class)
50
@ConditionalOnMissingBean({DataSource.class, XADataSource.class})
51
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource", matchIfMissing = true)
52
static class Hikari {
53
54
@Bean
55
@ConfigurationProperties(prefix = "spring.datasource.hikari")
56
HikariDataSource dataSource(DataSourceProperties properties) {
57
HikariDataSource dataSource = createDataSource(properties, HikariDataSource.class);
58
if (StringUtils.hasText(properties.getName())) {
59
dataSource.setPoolName(properties.getName());
60
}
61
return dataSource;
62
}
63
}
64
}
65
66
/**
67
* DataSource configuration properties
68
*/
69
@ConfigurationProperties(prefix = "spring.datasource")
70
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
71
72
/**
73
* Database connection URL
74
*/
75
private String url;
76
77
/**
78
* Database username
79
*/
80
private String username;
81
82
/**
83
* Database password
84
*/
85
private String password;
86
87
/**
88
* JDBC driver class name
89
*/
90
private String driverClassName;
91
92
/**
93
* DataSource type (connection pool implementation)
94
*/
95
private Class<? extends DataSource> type;
96
97
/**
98
* Connection pool name
99
*/
100
private String name;
101
102
/**
103
* Whether to generate a random datasource name
104
*/
105
private boolean generateUniqueName = true;
106
107
// Getters and setters
108
public String getUrl() { return this.url; }
109
public void setUrl(String url) { this.url = url; }
110
public String getUsername() { return this.username; }
111
public void setUsername(String username) { this.username = username; }
112
public String getPassword() { return this.password; }
113
public void setPassword(String password) { this.password = password; }
114
115
/**
116
* Create DataSourceBuilder for this configuration
117
* @return configured DataSourceBuilder
118
*/
119
public DataSourceBuilder<?> initializeDataSourceBuilder() {
120
return DataSourceBuilder.create(getClassLoader())
121
.type(getType())
122
.driverClassName(determineDriverClassName())
123
.url(determineUrl())
124
.username(determineUsername())
125
.password(determinePassword());
126
}
127
}
128
```
129
130
**Usage Examples:**
131
132
```java
133
// Properties configuration
134
# application.properties
135
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
136
spring.datasource.username=user
137
spring.datasource.password=password
138
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
139
140
# HikariCP specific configuration
141
spring.datasource.hikari.maximum-pool-size=20
142
spring.datasource.hikari.minimum-idle=5
143
spring.datasource.hikari.connection-timeout=30000
144
spring.datasource.hikari.idle-timeout=600000
145
spring.datasource.hikari.max-lifetime=1800000
146
147
// Custom DataSource configuration
148
@Configuration
149
public class DataSourceConfig {
150
151
@Bean
152
@Primary
153
@ConfigurationProperties("spring.datasource")
154
public DataSource primaryDataSource() {
155
return DataSourceBuilder.create().build();
156
}
157
158
@Bean
159
@ConfigurationProperties("spring.datasource.secondary")
160
public DataSource secondaryDataSource() {
161
return DataSourceBuilder.create().build();
162
}
163
}
164
```
165
166
### JPA and Hibernate Configuration
167
168
Auto-configuration for JPA (Java Persistence API) and Hibernate ORM.
169
170
```java { .api }
171
/**
172
* Auto-configuration for Hibernate JPA
173
* Configures EntityManagerFactory and transaction management
174
*/
175
@AutoConfiguration
176
@ConditionalOnClass({LocalContainerEntityManagerFactoryBean.class, EntityManager.class, SessionImplementor.class})
177
@ConditionalOnBean(DataSource.class)
178
@EnableConfigurationProperties(JpaProperties.class)
179
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
180
public class HibernateJpaAutoConfiguration extends JpaBaseConfiguration {
181
182
/**
183
* Creates Hibernate vendor adapter
184
*/
185
@Override
186
protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
187
return new HibernateJpaVendorAdapter();
188
}
189
190
/**
191
* Gets Hibernate-specific vendor properties
192
*/
193
@Override
194
protected Map<String, Object> getVendorProperties() {
195
Map<String, Object> vendorProperties = new LinkedHashMap<>();
196
vendorProperties.putAll(this.hibernateProperties.determineHibernateProperties(
197
getProperties().getProperties(), new HibernateSettings()));
198
return vendorProperties;
199
}
200
}
201
202
/**
203
* JPA configuration properties
204
*/
205
@ConfigurationProperties(prefix = "spring.jpa")
206
public class JpaProperties {
207
208
/**
209
* Additional native properties to set on the JPA provider
210
*/
211
private Map<String, String> properties = new HashMap<>();
212
213
/**
214
* Mapping resources (equivalent to persistence.xml entries)
215
*/
216
private List<String> mappingResources = new ArrayList<>();
217
218
/**
219
* Name of the target database to operate on
220
*/
221
private Database database;
222
223
/**
224
* Target database platform
225
*/
226
private String databasePlatform;
227
228
/**
229
* Whether to initialize the schema on startup
230
*/
231
private boolean generateDdl = false;
232
233
/**
234
* Whether to show SQL statements
235
*/
236
private boolean showSql = false;
237
238
/**
239
* Whether to defer DataSource initialization until after EntityManagerFactory initialization
240
*/
241
private Boolean deferDatasourceInitialization;
242
243
/**
244
* Hibernate-specific properties
245
*/
246
private final Hibernate hibernate = new Hibernate();
247
248
// Getters and setters
249
public Map<String, String> getProperties() { return this.properties; }
250
public void setProperties(Map<String, String> properties) { this.properties = properties; }
251
public boolean isShowSql() { return this.showSql; }
252
public void setShowSql(boolean showSql) { this.showSql = showSql; }
253
254
/**
255
* Hibernate-specific configuration
256
*/
257
public static class Hibernate {
258
259
/**
260
* DDL mode (none, validate, update, create, create-drop)
261
*/
262
private String ddlAuto;
263
264
/**
265
* Hibernate naming strategy
266
*/
267
private String namingStrategy;
268
269
/**
270
* Hibernate physical naming strategy
271
*/
272
private Class<?> physicalNamingStrategy;
273
274
/**
275
* Hibernate implicit naming strategy
276
*/
277
private Class<?> implicitNamingStrategy;
278
279
/**
280
* Whether to use SQL comments
281
*/
282
private Boolean useNewIdGeneratorMappings;
283
284
// Getters and setters
285
public String getDdlAuto() { return this.ddlAuto; }
286
public void setDdlAuto(String ddlAuto) { this.ddlAuto = ddlAuto; }
287
}
288
}
289
```
290
291
### Spring Data JPA Repositories
292
293
Auto-configuration for Spring Data JPA repositories.
294
295
```java { .api }
296
/**
297
* Auto-configuration for Spring Data JPA repositories
298
* Enables repository scanning and configuration
299
*/
300
@AutoConfiguration
301
@ConditionalOnBean(DataSource.class)
302
@ConditionalOnClass(JpaRepository.class)
303
@ConditionalOnMissingBean({JpaRepositoryFactoryBean.class, JpaRepositoryConfigExtension.class})
304
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
305
@EnableJpaRepositories
306
@AutoConfigureAfter(HibernateJpaAutoConfiguration.class)
307
public class JpaRepositoriesAutoConfiguration {
308
309
/**
310
* Configuration for audit-aware repositories
311
*/
312
@Configuration(proxyBeanMethods = false)
313
@ConditionalOnClass(AbstractAuditable.class)
314
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enable-default-transactions", havingValue = "true", matchIfMissing = true)
315
static class JpaRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport {
316
317
@Override
318
protected Class<? extends Annotation> getAnnotation() {
319
return EnableJpaRepositories.class;
320
}
321
322
@Override
323
protected Class<?> getConfiguration() {
324
return EnableJpaRepositoriesConfiguration.class;
325
}
326
327
@Override
328
protected RepositoryConfigurationExtension getRepositoryConfigurationExtension() {
329
return new JpaRepositoryConfigExtension();
330
}
331
}
332
}
333
334
/**
335
* Spring Data JPA configuration properties
336
*/
337
@ConfigurationProperties(prefix = "spring.data.jpa.repositories")
338
public class JpaRepositoriesProperties {
339
340
/**
341
* Whether to enable JPA repositories
342
*/
343
private boolean enabled = true;
344
345
/**
346
* Whether to enable default transactions for repository methods
347
*/
348
private boolean enableDefaultTransactions = true;
349
350
/**
351
* Bootstrap mode for JPA repositories
352
*/
353
private BootstrapMode bootstrapMode = BootstrapMode.DEFAULT;
354
355
// Getters and setters
356
public boolean isEnabled() { return this.enabled; }
357
public void setEnabled(boolean enabled) { this.enabled = enabled; }
358
public boolean isEnableDefaultTransactions() { return this.enableDefaultTransactions; }
359
public void setEnableDefaultTransactions(boolean enableDefaultTransactions) {
360
this.enableDefaultTransactions = enableDefaultTransactions;
361
}
362
363
public enum BootstrapMode {
364
DEFAULT, LAZY, DEFERRED
365
}
366
}
367
```
368
369
**Usage Examples:**
370
371
```java
372
// JPA Entity
373
@Entity
374
@Table(name = "users")
375
public class User {
376
@Id
377
@GeneratedValue(strategy = GenerationType.IDENTITY)
378
private Long id;
379
380
@Column(nullable = false, unique = true)
381
private String username;
382
383
@Column(nullable = false)
384
private String email;
385
386
// Constructors, getters, setters
387
}
388
389
// JPA Repository
390
@Repository
391
public interface UserRepository extends JpaRepository<User, Long> {
392
393
Optional<User> findByUsername(String username);
394
395
List<User> findByEmailContaining(String emailPattern);
396
397
@Query("SELECT u FROM User u WHERE u.email = ?1")
398
Optional<User> findByEmail(String email);
399
400
@Modifying
401
@Query("UPDATE User u SET u.email = ?2 WHERE u.id = ?1")
402
int updateEmailById(Long id, String email);
403
}
404
405
// Service using repository
406
@Service
407
@Transactional
408
public class UserService {
409
410
private final UserRepository userRepository;
411
412
public UserService(UserRepository userRepository) {
413
this.userRepository = userRepository;
414
}
415
416
public User createUser(String username, String email) {
417
User user = new User(username, email);
418
return userRepository.save(user);
419
}
420
421
@Transactional(readOnly = true)
422
public Optional<User> findByUsername(String username) {
423
return userRepository.findByUsername(username);
424
}
425
}
426
427
// Properties configuration
428
# application.properties
429
spring.jpa.hibernate.ddl-auto=update
430
spring.jpa.show-sql=true
431
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
432
spring.jpa.properties.hibernate.format_sql=true
433
spring.data.jpa.repositories.enabled=true
434
```
435
436
### NoSQL Database Configuration
437
438
Auto-configurations for popular NoSQL databases.
439
440
```java { .api }
441
/**
442
* Auto-configuration for MongoDB
443
* Configures MongoDB client and template
444
*/
445
@AutoConfiguration
446
@ConditionalOnClass(MongoClient.class)
447
@EnableConfigurationProperties(MongoProperties.class)
448
public class MongoAutoConfiguration {
449
450
/**
451
* Creates MongoDB client
452
*/
453
@Bean
454
@ConditionalOnMissingBean(type = "com.mongodb.client.MongoClient")
455
public MongoClient mongo(MongoProperties properties, ObjectProvider<MongoClientCustomizer> customizers) {
456
return new MongoClientFactory(properties, customizers).createMongoClient();
457
}
458
}
459
460
/**
461
* Auto-configuration for Redis
462
* Configures Redis connection factory and template
463
*/
464
@AutoConfiguration
465
@ConditionalOnClass(RedisOperations.class)
466
@EnableConfigurationProperties(RedisProperties.class)
467
public class RedisAutoConfiguration {
468
469
/**
470
* Configuration for Jedis Redis client
471
*/
472
@Configuration(proxyBeanMethods = false)
473
@ConditionalOnClass({GenericObjectPool.class, JedisConnection.class, Jedis.class})
474
static class JedisConnectionConfiguration extends RedisConnectionConfiguration {
475
476
@Bean
477
@ConditionalOnMissingBean(RedisConnectionFactory.class)
478
JedisConnectionFactory redisConnectionFactory(
479
ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers) {
480
return createJedisConnectionFactory(builderCustomizers);
481
}
482
}
483
484
/**
485
* Creates Redis template
486
*/
487
@Bean
488
@ConditionalOnMissingBean(name = "redisTemplate")
489
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
490
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
491
RedisTemplate<Object, Object> template = new RedisTemplate<>();
492
template.setConnectionFactory(redisConnectionFactory);
493
return template;
494
}
495
496
/**
497
* Creates string Redis template
498
*/
499
@Bean
500
@ConditionalOnMissingBean
501
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
502
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
503
return new StringRedisTemplate(redisConnectionFactory);
504
}
505
}
506
507
/**
508
* Redis configuration properties
509
*/
510
@ConfigurationProperties(prefix = "spring.data.redis")
511
public class RedisProperties {
512
513
/**
514
* Database index used by the connection factory
515
*/
516
private int database = 0;
517
518
/**
519
* Redis server host
520
*/
521
private String host = "localhost";
522
523
/**
524
* Redis server port
525
*/
526
private int port = 6379;
527
528
/**
529
* Login password of the Redis instance
530
*/
531
private String password;
532
533
/**
534
* Whether to enable SSL support
535
*/
536
private boolean ssl;
537
538
/**
539
* Connection timeout
540
*/
541
private Duration timeout;
542
543
/**
544
* Client name to be set on connections
545
*/
546
private String clientName;
547
548
/**
549
* Type of client to use
550
*/
551
private ClientType clientType = ClientType.JEDIS;
552
553
/**
554
* Connection pooling properties
555
*/
556
private final Pool pool = new Pool();
557
558
/**
559
* Cluster properties
560
*/
561
private final Cluster cluster = new Cluster();
562
563
/**
564
* Sentinel properties
565
*/
566
private final Sentinel sentinel = new Sentinel();
567
568
// Getters and setters
569
public String getHost() { return this.host; }
570
public void setHost(String host) { this.host = host; }
571
public int getPort() { return this.port; }
572
public void setPort(int port) { this.port = port; }
573
574
public enum ClientType {
575
JEDIS, LETTUCE
576
}
577
578
/**
579
* Pool properties for connection pooling
580
*/
581
public static class Pool {
582
private Boolean enabled;
583
private int maxIdle = 8;
584
private int minIdle = 0;
585
private int maxActive = 8;
586
private Duration maxWait = Duration.ofMillis(-1);
587
private Duration timeBetweenEvictionRuns;
588
}
589
}
590
```
591
592
**Usage Examples:**
593
594
```java
595
// MongoDB usage
596
@Document(collection = "products")
597
public class Product {
598
@Id
599
private String id;
600
private String name;
601
private BigDecimal price;
602
private List<String> categories;
603
604
// Constructors, getters, setters
605
}
606
607
@Repository
608
public interface ProductRepository extends MongoRepository<Product, String> {
609
List<Product> findByNameContaining(String name);
610
List<Product> findByCategoriesIn(List<String> categories);
611
List<Product> findByPriceBetween(BigDecimal minPrice, BigDecimal maxPrice);
612
}
613
614
// Redis usage
615
@Service
616
public class CacheService {
617
618
private final RedisTemplate<String, Object> redisTemplate;
619
private final StringRedisTemplate stringRedisTemplate;
620
621
public CacheService(RedisTemplate<String, Object> redisTemplate,
622
StringRedisTemplate stringRedisTemplate) {
623
this.redisTemplate = redisTemplate;
624
this.stringRedisTemplate = stringRedisTemplate;
625
}
626
627
public void cacheUser(String key, User user) {
628
redisTemplate.opsForValue().set(key, user, Duration.ofMinutes(30));
629
}
630
631
public User getCachedUser(String key) {
632
return (User) redisTemplate.opsForValue().get(key);
633
}
634
635
public void cacheString(String key, String value) {
636
stringRedisTemplate.opsForValue().set(key, value, Duration.ofHours(1));
637
}
638
}
639
640
// Properties configuration
641
# MongoDB
642
spring.data.mongodb.uri=mongodb://localhost:27017/mydb
643
spring.data.mongodb.database=myapp
644
645
# Redis
646
spring.data.redis.host=localhost
647
spring.data.redis.port=6379
648
spring.data.redis.password=secret
649
spring.data.redis.timeout=2000ms
650
spring.data.redis.jedis.pool.max-active=8
651
spring.data.redis.jedis.pool.max-idle=8
652
spring.data.redis.jedis.pool.min-idle=0
653
```
654
655
## Types
656
657
### Data Configuration Types
658
659
```java { .api }
660
/**
661
* Enumeration of supported databases for JPA
662
*/
663
public enum Database {
664
DEFAULT, H2, HSQL, MYSQL, ORACLE, POSTGRESQL, SQL_SERVER, DB2, INFORMIX, HANA, DERBY
665
}
666
667
/**
668
* Interface for customizing DataSource instances
669
*/
670
public interface DataSourceCustomizer {
671
/**
672
* Customize the specified DataSource
673
* @param dataSource the DataSource to customize
674
*/
675
void customize(DataSource dataSource);
676
}
677
678
/**
679
* Interface for customizing connection pool DataSource instances
680
*/
681
@FunctionalInterface
682
public interface ConnectionPoolDataSourceCustomizer<T extends DataSource> {
683
/**
684
* Customize the connection pool DataSource
685
* @param dataSource the DataSource to customize
686
*/
687
void customize(T dataSource);
688
}
689
690
/**
691
* JPA entity manager factory customizer
692
*/
693
@FunctionalInterface
694
public interface EntityManagerFactoryBuilderCustomizer {
695
/**
696
* Customize the EntityManagerFactoryBuilder
697
* @param builder the builder to customize
698
*/
699
void customize(EntityManagerFactoryBuilder builder);
700
}
701
```