Spring JdbcTemplate整合使用方法及原理詳解
基本配置
JdbcTemplate基本用法實(shí)際上很簡(jiǎn)單,開(kāi)發(fā)者在創(chuàng)建一個(gè)SpringBoot項(xiàng)目時(shí),除了選擇基本的Web依賴,再記得選上Jdbc依賴,以及數(shù)據(jù)庫(kù)驅(qū)動(dòng)依賴即可,如下:
項(xiàng)目創(chuàng)建成功之后,記得添加Druid數(shù)據(jù)庫(kù)連接池依賴(注意這里可以添加專門為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>
項(xiàng)目創(chuàng)建完后,接下來(lái)只需要在application.properties中提供數(shù)據(jù)的基本配置即可,如下:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.username=rootspring.datasource.password=123spring.datasource.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=UTF-8
如此之后,所有的配置就算完成了,接下來(lái)就可以直接使用JdbcTemplate了?咋這么方便呢?其實(shí)這就是SpringBoot的自動(dòng)化配置帶來(lái)的好處,我們先說(shuō)用法,一會(huì)來(lái)說(shuō)原理。
基本用法
首先我們來(lái)創(chuàng)建一個(gè)User Bean,如下:
public class User { private Long id; private String username; private String address; //省略getter/setter}
然后來(lái)創(chuàng)建一個(gè)UserService類,在UserService類中注入JdbcTemplate,如下:
@Servicepublic class UserService { @Autowired JdbcTemplate jdbcTemplate;}
好了,如此之后,準(zhǔn)備工作就算完成了。
增
JdbcTemplate中,除了查詢有幾個(gè)API之外,增刪改統(tǒng)一都使用update來(lái)操作,自己來(lái)傳入SQL即可。例如添加數(shù)據(jù),方法如下:
public int addUser(User user) { return jdbcTemplate.update('insert into user (username,address) values (?,?);', user.getUsername(), user.getAddress());}
update方法的返回值就是SQL執(zhí)行受影響的行數(shù)。
這里只需要傳入SQL即可,如果你的需求比較復(fù)雜,例如在數(shù)據(jù)插入的過(guò)程中希望實(shí)現(xiàn)主鍵回填,那么可以使用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;}
實(shí)際上這里就相當(dāng)于完全使用了JDBC中的解決方案了,首先在構(gòu)建PreparedStatement時(shí)傳入Statement.RETURN_GENERATED_KEYS,然后傳入KeyHolder,最終從KeyHolder中獲取剛剛插入數(shù)據(jù)的id保存到user對(duì)象的id屬性中去。
你能想到的JDBC的用法,在這里都能實(shí)現(xiàn),Spring提供的JdbcTemplate雖然不如MyBatis,但是比起Jdbc還是要方便很多的。
刪
刪除也是使用update API,傳入你的SQL即可:
public int deleteUserById(Long id) { return jdbcTemplate.update('delete from user where id=?', id);}
當(dāng)然你也可以使用PreparedStatementCreator。
改
public int updateUserById(User user) { return jdbcTemplate.update('update user set username=?,address=? where id=?', user.getUsername(), user.getAddress(),user.getId());}
當(dāng)然你也可以使用PreparedStatementCreator。
查
查詢的話,稍微有點(diǎn)變化,這里主要向大伙介紹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; } });}
查詢的時(shí)候需要提供一個(gè)RowMapper,就是需要自己手動(dòng)映射,將數(shù)據(jù)庫(kù)中的字段和對(duì)象的屬性一一對(duì)應(yīng)起來(lái),這樣。。。。嗯看起來(lái)有點(diǎn)麻煩,實(shí)際上,如果數(shù)據(jù)庫(kù)中的字段和對(duì)象屬性的名字一模一樣的話,有另外一個(gè)簡(jiǎn)單的方案,如下:
public List<User> getAllUsers2() { return jdbcTemplate.query('select * from user', new BeanPropertyRowMapper<>(User.class));}
至于查詢時(shí)候傳參也是使用占位符,這個(gè)和前文的一致,這里不再贅述。
其他
除了這些基本用法之外,JdbcTemplate也支持其他用法,例如調(diào)用存儲(chǔ)過(guò)程等,這些都比較容易,而且和Jdbc本身都比較相似,這里也就不做介紹了,有興趣可以留言討論。
原理分析
那么在SpringBoot中,配置完數(shù)據(jù)庫(kù)基本信息之后,就有了一個(gè)JdbcTemplate了,這個(gè)東西是從哪里來(lái)的呢?源碼在
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); }}}
從這個(gè)類中,大致可以看出,當(dāng)當(dāng)前類路徑下存在DataSource和JdbcTemplate時(shí),該類就會(huì)被自動(dòng)配置,jdbcTemplate方法則表示,如果開(kāi)發(fā)者沒(méi)有自己提供一個(gè)JdbcOperations的實(shí)例的話,系統(tǒng)就自動(dòng)配置一個(gè)JdbcTemplate Bean(JdbcTemplate是JdbcOperations接口的一個(gè)實(shí)現(xiàn))。好了,不知道大伙有沒(méi)有收獲呢?
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫(huà)水平條形圖案例2. python中PyQuery庫(kù)用法分享3. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說(shuō)明4. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效5. 使用css實(shí)現(xiàn)全兼容tooltip提示框6. Python編寫nmap掃描工具7. JavaScript實(shí)現(xiàn)組件化和模塊化方法詳解8. .NET6打包部署到Windows Service的全過(guò)程9. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享10. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值
