Spring Boot2 系列教程(十九)Spring Boot 整合 JdbcTemplate

  • 2019 年 11 月 6 日
  • 筆記

在 Java 領域,數據持久化有幾個常見的方案,有 Spring 自帶的 JdbcTemplate 、有 MyBatis,還有 JPA,在這些方案中,最簡單的就是 Spring 自帶的 JdbcTemplate 了,這個東西雖然沒有 MyBatis 那麼方便,但是比起最開始的 Jdbc 已經強了很多了,它沒有 MyBatis 功能那麼強大,當然也意味着它的使用比較簡單,事實上,JdbcTemplate 算是最簡單的數據持久化方案了,本文就和大夥來說說這個東西的使用。

1. 基本配置

JdbcTemplate 基本用法實際上很簡單,開發者在創建一個 SpringBoot 項目時,除了選擇基本的 Web 依賴,再記得選上 Jdbc 依賴,以及數據庫驅動依賴即可,如下:

項目創建成功之後,記得添加 Druid 數據庫連接池依賴(注意這裡可以添加專門為 Spring Boot 打造的 druid-spring-boot-starter,而不是我們一般在 SSM 中添加的 Druid),所有添加的依賴如下:

<dependency>      <groupId>com.alibaba</groupId>      <artifactId>druid-spring-boot-starter</artifactId>      <version>1.1.10</version>  </dependency>  <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-jdbc</artifactId>  </dependency>  <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <dependency>      <groupId>mysql</groupId>      <artifactId>mysql-connector-java</artifactId>      <version>5.1.27</version>      <scope>runtime</scope>  </dependency>  

項目創建完後,接下來只需要在 application.properties 中提供數據的基本配置即可,如下:

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource  spring.datasource.username=root  spring.datasource.password=123  spring.datasource.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=UTF-8  

如此之後,所有的配置就算完成了,接下來就可以直接使用 JdbcTemplate 了?咋這麼方便呢?其實這就是 SpringBoot 的自動化配置帶來的好處,我們先說用法,一會來說原理。

2. 基本用法

首先我們來創建一個 User Bean,如下:

public class User {      private Long id;      private String username;      private String address;      //省略getter/setter  }  

然後來創建一個 UserService 類,在 UserService 類中注入 JdbcTemplate ,如下:

@Service  public class UserService {      @Autowired      JdbcTemplate jdbcTemplate;  }  

好了,如此之後,準備工作就算完成了。

2.1 增

JdbcTemplate 中,除了查詢有幾個 API 之外,增刪改統一都使用 update 來操作,自己來傳入 SQL 即可。例如添加數據,方法如下:

public int addUser(User user) {      return jdbcTemplate.update("insert into user (username,address) values (?,?);", user.getUsername(), user.getAddress());  }  

update 方法的返回值就是 SQL 執行受影響的行數。

這裡只需要傳入 SQL 即可,如果你的需求比較複雜,例如在數據插入的過程中希望實現主鍵回填,那麼可以使用 PreparedStatementCreator,如下:

public int addUser2(User user) {      KeyHolder keyHolder = new GeneratedKeyHolder();      int update = jdbcTemplate.update(new PreparedStatementCreator() {          @Override          public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {              PreparedStatement ps = connection.prepareStatement("insert into user (username,address) values (?,?);", Statement.RETURN_GENERATED_KEYS);              ps.setString(1, user.getUsername());              ps.setString(2, user.getAddress());              return ps;          }      }, keyHolder);      user.setId(keyHolder.getKey().longValue());      System.out.println(user);      return update;  }  

實際上這裡就相當於完全使用了 JDBC 中的解決方案了,首先在構建 PreparedStatement 時傳入 Statement.RETURN_GENERATED_KEYS,然後傳入 KeyHolder,最終從 KeyHolder 中獲取剛剛插入數據的 id 保存到 user 對象的 id 屬性中去。

你能想到的 JDBC 的用法,在這裡都能實現,Spring 提供的 JdbcTemplate 雖然不如 MyBatis,但是比起 Jdbc 還是要方便很多的。

2.2 刪

刪除也是使用 update API,傳入你的 SQL 即可:

public int deleteUserById(Long id) {      return jdbcTemplate.update("delete from user where id=?", id);  }  

當然你也可以使用 PreparedStatementCreator。

2.3 改

public int updateUserById(User user) {      return jdbcTemplate.update("update user set username=?,address=? where id=?", user.getUsername(), user.getAddress(),user.getId());  }  

當然你也可以使用 PreparedStatementCreator。

2.4 查

查詢的話,稍微有點變化,這裡主要向大夥介紹 query 方法,例如查詢所有用戶:

public List<User> getAllUsers() {      return jdbcTemplate.query("select * from user", new RowMapper<User>() {          @Override          public User mapRow(ResultSet resultSet, int i) throws SQLException {              String username = resultSet.getString("username");              String address = resultSet.getString("address");              long id = resultSet.getLong("id");              User user = new User();              user.setAddress(address);              user.setUsername(username);              user.setId(id);              return user;          }      });  }  

查詢的時候需要提供一個 RowMapper,就是需要自己手動映射,將數據庫中的字段和對象的屬性一一對應起來,這樣。。。。嗯看起來有點麻煩,實際上,如果數據庫中的字段和對象屬性的名字一模一樣的話,有另外一個簡單的方案,如下:

public List<User> getAllUsers2() {      return jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));  }  

至於查詢時候傳參也是使用佔位符,這個和前文的一致,這裡不再贅述。

2.5 其他

除了這些基本用法之外,JdbcTemplate 也支持其他用法,例如調用存儲過程等,這些都比較容易,而且和 Jdbc 本身都比較相似,這裡也就不做介紹了,有興趣可以留言討論。

3. 原理分析

那麼在 SpringBoot 中,配置完數據庫基本信息之後,就有了一個 JdbcTemplate 了,這個東西是從哪裡來的呢?源碼在 org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration 類中,該類源碼如下:

@Configuration  @ConditionalOnClass({ DataSource.class, JdbcTemplate.class })  @ConditionalOnSingleCandidate(DataSource.class)  @AutoConfigureAfter(DataSourceAutoConfiguration.class)  @EnableConfigurationProperties(JdbcProperties.class)  public class JdbcTemplateAutoConfiguration {  	@Configuration  	static class JdbcTemplateConfiguration {  		private final DataSource dataSource;  		private final JdbcProperties properties;  		JdbcTemplateConfiguration(DataSource dataSource, JdbcProperties properties) {  			this.dataSource = dataSource;  			this.properties = properties;  		}  		@Bean  		@Primary  		@ConditionalOnMissingBean(JdbcOperations.class)  		public JdbcTemplate jdbcTemplate() {  			JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);  			JdbcProperties.Template template = this.properties.getTemplate();  			jdbcTemplate.setFetchSize(template.getFetchSize());  			jdbcTemplate.setMaxRows(template.getMaxRows());  			if (template.getQueryTimeout() != null) {  				jdbcTemplate  						.setQueryTimeout((int) template.getQueryTimeout().getSeconds());  			}  			return jdbcTemplate;  		}  	}  	@Configuration  	@Import(JdbcTemplateConfiguration.class)  	static class NamedParameterJdbcTemplateConfiguration {  		@Bean  		@Primary  		@ConditionalOnSingleCandidate(JdbcTemplate.class)  		@ConditionalOnMissingBean(NamedParameterJdbcOperations.class)  		public NamedParameterJdbcTemplate namedParameterJdbcTemplate(  				JdbcTemplate jdbcTemplate) {  			return new NamedParameterJdbcTemplate(jdbcTemplate);  		}  	}  }  

從這個類中,大致可以看出,噹噹前類路徑下存在 DataSource 和 JdbcTemplate 時,該類就會被自動配置,jdbcTemplate 方法則表示,如果開發者沒有自己提供一個 JdbcOperations 的實例的話,系統就自動配置一個 JdbcTemplate Bean(JdbcTemplate 是 JdbcOperations 接口的一個實現)。好了,不知道大夥有沒有收穫呢?