Spring JdbcTemplate整合使用方法及原理詳解
基本配置
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.DruidDataSourcespring.datasource.username=rootspring.datasource.password=123spring.datasource.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=UTF-8
如此之后,所有的配置就算完成了,接下來就可以直接使用JdbcTemplate了?咋這么方便呢?其實這就是SpringBoot的自動化配置帶來的好處,我們先說用法,一會來說原理。
基本用法
首先我們來創建一個User Bean,如下:
public class User { private Long id; private String username; private String address; //省略getter/setter}
然后來創建一個UserService類,在UserService類中注入JdbcTemplate,如下:
@Servicepublic class UserService { @Autowired JdbcTemplate jdbcTemplate;}
好了,如此之后,準備工作就算完成了。
增
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還是要方便很多的。
刪
刪除也是使用update API,傳入你的SQL即可:
public int deleteUserById(Long id) { return jdbcTemplate.update('delete from user where id=?', id);}
當然你也可以使用PreparedStatementCreator。
改
public int updateUserById(User user) { return jdbcTemplate.update('update user set username=?,address=? where id=?', user.getUsername(), user.getAddress(),user.getId());}
當然你也可以使用PreparedStatementCreator。
查
查詢的話,稍微有點變化,這里主要向大伙介紹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));}
至于查詢時候傳參也是使用占位符,這個和前文的一致,這里不再贅述。
其他
除了這些基本用法之外,JdbcTemplate也支持其他用法,例如調用存儲過程等,這些都比較容易,而且和Jdbc本身都比較相似,這里也就不做介紹了,有興趣可以留言討論。
原理分析
那么在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接口的一個實現)。好了,不知道大伙有沒有收獲呢?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: