Chapter 12: Using data sources in Spring apps
The introduction explains why database persistence matters to Spring apps and introduces the chapter’s topic without teaching its implementation.
After this chapter you will be able to
- Need for database persistence. Explain why Spring apps often need databases: applications need to store data they work with, and relational databases are a widely applicable way to persist it.
- Data source responsibilities and benefits. Explain how a data source manages an app’s connections to a DBMS, keeping connection management out of business logic and avoiding unnecessary new connections.
- JDBC abstractions and drivers. Distinguish the JDBC abstractions supplied by the JDK from the vendor-provided JDBC driver needed to connect to a particular DBMS technology.
- JdbcTemplate data mutations. Explain why the example uses JdbcTemplate instead of plain JDBC and how its update() method changes stored data.
- Repository bean configuration. Explain how the example makes PurchaseRepository available to the controller and obtains a JdbcTemplate for it.
- RowMapper result conversion. Explain how the repository retrieves purchases as Purchase objects.
- Purchase endpoint flow. Trace how clients use the two endpoints to store a purchase and retrieve purchases.
- H2 and production data sources. Explain why H2 is useful for examples and getting started with persistence, while production apps often need more than an in-memory database and require data source configuration.
- External database configuration. Describe the two changes needed to switch the example from H2 to MySQL, and explain how Spring Boot uses the connection properties to create a DataSource bean.
- Reasons for a custom DataSource. Explain when defining a DataSource bean yourself is preferable to relying on Spring Boot to create one from application properties.
- Custom bean configuration. Describe how the section adds a custom DataSource to the Spring context and supplies values for its configuration.
What it builds on
- Using autoconfiguration by convention based on dependencies (chapter 7) · Spring Boot can configure components by convention.
- Using stereotype annotations to create beans (chapter 2) · Stereotype annotations add beans to the Spring context.
- Implementing REST endpoints (chapter 10) · REST endpoints expose application actions to clients.
- Using the @Bean annotation to create beans (chapter 2) · Defining Spring beans with @Bean
Section by section
Introduction
The introduction explains why database persistence matters to Spring apps and introduces the chapter’s topic without teaching its implementation.
- Need for database persistence: Explain why Spring apps often need databases: applications need to store data they work with, and relational databases are a widely applicable way to persist it.
Why it matters: This is the reason the chapter turns to database access in Spring apps.
Key terms: persist data, relational databases, Spring apps
12.1 What a data source is
This section explains why Spring apps use a data source to manage database connections and how JDBC drivers enable connections to specific DBMS technologies.
- Data source responsibilities and benefits: Explain how a data source manages an app’s connections to a DBMS, keeping connection management out of business logic and avoiding unnecessary new connections.
Why it matters: It explains both why Spring persistence tools expect a data source and why the app should not manage every connection itself. - JDBC abstractions and drivers: Distinguish the JDBC abstractions supplied by the JDK from the vendor-provided JDBC driver needed to connect to a particular DBMS technology.
Why it matters: A data source still needs a driver that can connect to the particular database technology the app uses. - Spring Boot data source default: State which data source implementation Spring Boot uses by default and relate it to the section’s discussion of connection management.
Why it matters: It identifies the concrete data source implementation used by default in the book’s Spring Boot examples.
Key terms: data source, connection, DBMS, persistence layer, JDBC, JDK, JDBC driver, runtime dependency, HikariCP, Hikari connection pool
12.2 Using JdbcTemplate to work with persisted data
This section builds a small Spring app that uses JdbcTemplate to store and retrieve purchases through REST endpoints.
- JdbcTemplate data mutations: Explain why the example uses JdbcTemplate instead of plain JDBC and how its update() method changes stored data.
Why it matters: It explains what JdbcTemplate simplifies in the purchase repository. - Purchase data setup: Describe how the example defines purchase data in the database and in Java.
Why it matters: The repository needs a table to query and objects in which to represent its purchases. - Repository bean configuration: Explain how the example makes PurchaseRepository available to the controller and obtains a JdbcTemplate for it.
Why it matters: It connects the database-working class to the Spring-managed objects it uses. - Database failure handling: Explain what happens to SQL exceptions under JdbcTemplate and how the application can respond to failures.
Why it matters: Less exception-handling boilerplate does not remove the need to decide how the app responds to a failed operation. - RowMapper result conversion: Explain how the repository retrieves purchases as Purchase objects.
Why it matters: A SELECT result must be converted into the model objects the rest of the app uses. - Purchase endpoint flow: Trace how clients use the two endpoints to store a purchase and retrieve purchases.
Why it matters: It ties the database operations to the behavior a client can observe.
Key terms: JdbcTemplate, update(), JDBC, INSERT, UPDATE, DELETE, purchase, schema.sql, DDL, BigDecimal
12.3 Customizing the configuration of the data source
This section explains why a production app may need a configured data source rather than the in-memory H2 database used to get started.
- H2 and production data sources: Explain why H2 is useful for examples and getting started with persistence, while production apps often need more than an in-memory database and require data source configuration.
Why it matters: This distinction explains why the example moves beyond its initial H2 setup.
Key terms: H2 database, in-memory database, data source, production apps
12.3.1 Defining the data source in the application properties file
This subsection shows how to switch a Spring app from H2 to an external MySQL database by changing dependencies and application properties, then verify that purchases are persisted.
- External database configuration: Describe the two changes needed to switch the example from H2 to MySQL, and explain how Spring Boot uses the connection properties to create a DataSource bean.
Why it matters: These changes let the existing app connect to an external database rather than H2. - External database schema initialization: Explain why the example sets spring.sql.init.mode to always for MySQL and how this differs from H2.
Why it matters: A working connection alone does not ensure the example’s purchase table is created. - Purchase persistence verification: Describe how the example checks that a purchase was stored after changing the data source.
Why it matters: The endpoint check demonstrates that the reconfigured app can store and retrieve a record. - Production secret storage: Distinguish the example’s use of a password in application.properties from recommended production practice.
Why it matters: It prevents copying a tutorial’s credential-handling shortcut into a production app.
Key terms: H2, JDBC driver, application.properties, spring.datasource.url, spring.datasource.username, spring.datasource.password, spring.sql.init.mode, always, schema.sql, purchase table
12.3.2 Using a custom DataSource bean
Explains when to define a custom DataSource bean, how to configure it, and how to check that the app still persists purchases.
- Reasons for a custom DataSource: Explain when defining a DataSource bean yourself is preferable to relying on Spring Boot to create one from application properties.
Why it matters: It helps you decide whether Boot’s simpler configuration is enough or your app needs control over DataSource creation. - Custom bean configuration: Describe how the section adds a custom DataSource to the Spring context and supplies values for its configuration.
Why it matters: It separates creating the DataSource yourself from letting Spring Boot create it using its own properties. - Purchase persistence check: Describe how the example checks that the app using the custom DataSource still stores purchase records.
Why it matters: The POST-then-GET check shows that switching to a custom DataSource bean preserves the app’s persistence behavior.
Key terms: DataSource, Spring Boot, qualifiers, @Bean, @Value, application.properties, Spring context, HTTP POST, HTTP GET, /purchase
12.4 Questions
This section lists questions for reviewing the chapter’s concepts; answers are provided in Appendix A.
12.5 Summary
Summarizes how JDBC drivers, data sources, and JdbcTemplate support relational database access in Spring Boot, including when to customize them.
Where this is used later
- (chapter intro) (chapter 14) · The earlier discussion of how Spring apps use data sources.
- What Spring Data is (chapter 14) · Provides a point of comparison for another Spring approach to persistence.
- Using transactions in Spring apps (chapter 13) · Using JdbcTemplate to read and update persisted data
Concepts explained in this chapter
- DataSourceDataSource is an API abstraction that provides connections to a database.
- JdbcTemplateJdbcTemplate is a Spring API component that simplifies JDBC database access by handling recurring connection, statement, and result-processing code.
- JdbcTemplate update methodThe JdbcTemplate update method executes a SQL statement that changes database data and returns an update count.
- BigDecimalBigDecimal is a Java numeric type that represents decimal values with arbitrary precision and is suitable for exact monetary calculations.
- RowMapperA RowMapper is a Spring JDBC callback interface that converts one row of a result set into an application object.
- DataAccessExceptionDataAccessException is Spring's unchecked base exception type for data-access failures.
- relational databaseA relational database organizes data into related tables of rows and columns.
- repository annotationThe Spring @Repository stereotype annotation marks a class as a data-access component eligible for bean registration.
- JDBC driverA JDBC driver is a database-specific software component that implements JDBC interfaces to enable Java applications to communicate with a relational database.
- HikariCPHikariCP is an open-source JDBC connection-pooling library that provides a data source implementation for Java applications.
- database connectionA database connection is an active communication link between an application and a database server.
- database management systemA database management system (DBMS) is software for storing, retrieving, modifying, and managing data in databases.
- Spring BootSpring Boot is a Spring ecosystem project that provides convention-based default configuration for Spring applications.
- application.propertiesapplication.properties is a Spring Boot configuration file that defines application settings as key-value pairs.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
