This paper summarizes the tenth chapter of Spring Practice
Data access philosophy
The best practice is to put the functionality of data access into one or more components that focus on that task. Such a component is often called a Data Access Object (DAO) or Repository.
To avoid being coupled together to apply specific data access policies, a well-written Repository should expose functionality as an interface.
Take Spittr for example:
Entity classes (property, setter, getter) : Spitter, Spittle
Interfaces (define operations CRUD) : SpitterRepository, SpittleRepository
Implementation: JdbcSpitterRepository, jDBCSpittlepository
Configuring a Data Source
Spring provides several ways to configure data source beans in a Spring context, including:
- Data sources defined through the JDBC driver
- Data source lookup through JDNI
- Data source for connection pool
Because the project is small, the focus is on data sources defined through the JDBC driver, which is also the easiest way to configure
Jdbc-based data source
Spring provides three such data sources (. Are located in the org. Springframework. JDBC datasource in the package)
- DriverManagerDataSource
- SimpleDriverDataSource
- SingleConnectionDataSource
The differences between the three are detailed in the book “Spring In Action”
Here is how to configure DriverManagerDataSource
@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/spittr");
ds.setUsername("xxx");
ds.setPassword("xxx");
return ds;
}
Copy the code
Using JDBC Templates
Spring provides three template classes for JDBC to choose from
- JdbcTemplate
- NamedParameterJdbcTemplate
- SimpleJdbcTemplate
Since Spring3.1 SimpleJdbcTemplate has been abandoned, only need to use named parameters, only need to use the NamedParameterJdbcTemplate. As such, JdbcTemplate is the best choice for JDBC tasks.
Configured JdbcTemplate
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
Copy the code
A DataSource is injected via the constructor argument, where it can be any implementation of Javax.sql.DataSource, including the one mentioned above.
Assemble the JdbcTemplate into the Repository
@Bean
public SpitterRepository spitterRepository(JdbcTemplate jdbcTemplate) {
return new JdbcSpitterRepository(jdbcTemplate);
}
Copy the code
Configure the transaction manager
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
Copy the code
Transaction manager details