Spring JdbcTemplate整合使用方法及原理詳解
基本配置
JdbcTemplate基本用法實(shí)際上很簡單,開發(fā)者在創(chuàng)建一個(gè)SpringBoot項(xiàng)目時(shí),除了選擇基本的Web依賴,再記得選上Jdbc依賴,以及數(shù)據(jù)庫驅(qū)動(dòng)依賴即可,如下:

項(xiàng)目創(chuàng)建成功之后,記得添加Druid數(shù)據(jù)庫連接池依賴(注意這里可以添加專門為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)建完后,接下來只需要在application.properties中提供數(shù)據(jù)的基本配置即可,如下:
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了?咋這么方便呢?其實(shí)這就是SpringBoot的自動(dòng)化配置帶來的好處,我們先說用法,一會來說原理。
基本用法
首先我們來創(chuàng)建一個(gè)User Bean,如下:
public class User {
private Long id;
private String username;
private String address;
//省略getter/setter
}
然后來創(chuàng)建一個(gè)UserService類,在UserService類中注入JdbcTemplate,如下:
@Service
public class UserService {
@Autowired
JdbcTemplate jdbcTemplate;
}
好了,如此之后,準(zhǔn)備工作就算完成了。
增
JdbcTemplate中,除了查詢有幾個(gè)API之外,增刪改統(tǒng)一都使用update來操作,自己來傳入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ù)插入的過程中希望實(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對象的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ù)庫中的字段和對象的屬性一一對應(yīng)起來,這樣。。。。嗯看起來有點(diǎn)麻煩,實(shí)際上,如果數(shù)據(jù)庫中的字段和對象屬性的名字一模一樣的話,有另外一個(gè)簡單的方案,如下:
public List<User> getAllUsers2() {
return jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
}
至于查詢時(shí)候傳參也是使用占位符,這個(gè)和前文的一致,這里不再贅述。
其他
除了這些基本用法之外,JdbcTemplate也支持其他用法,例如調(diào)用存儲過程等,這些都比較容易,而且和Jdbc本身都比較相似,這里也就不做介紹了,有興趣可以留言討論。
原理分析
那么在SpringBoot中,配置完數(shù)據(jù)庫基本信息之后,就有了一個(gè)JdbcTemplate了,這個(gè)東西是從哪里來的呢?源碼在
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í),該類就會被自動(dòng)配置,jdbcTemplate方法則表示,如果開發(fā)者沒有自己提供一個(gè)JdbcOperations的實(shí)例的話,系統(tǒng)就自動(dòng)配置一個(gè)JdbcTemplate Bean(JdbcTemplate是JdbcOperations接口的一個(gè)實(shí)現(xiàn))。好了,不知道大伙有沒有收獲呢?
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
圖解Java中歸并排序算法的原理與實(shí)現(xiàn)
歸并排序是建立在歸并操作上的一種有效的排序算法。該算法是采用分治法(Divide and Conquer)的一個(gè)非常典型的應(yīng)用。本文將通過圖片詳解插入排序的原理及實(shí)現(xiàn),需要的可以參考一下2022-08-08
一文詳解Spring任務(wù)執(zhí)行和調(diào)度(小結(jié))
這篇文章主要介紹了一文詳解Spring任務(wù)執(zhí)行和調(diào)度(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
分享Java性能調(diào)優(yōu)的11個(gè)實(shí)用技巧
這些建議中的大多數(shù)都是基于Java的,但是也不一定,也有一些是可以應(yīng)用于所有的應(yīng)用程序和編程語言的。在我們分享基于Java的性能調(diào)優(yōu)技巧之前,讓我們先討論一下這些通用的性能調(diào)優(yōu)技巧2017-11-11
詳解Spring boot上配置與使用mybatis plus
這篇文章主要介紹了詳解Spring boot上配置與使用mybatis plus,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05
SpringBoot實(shí)現(xiàn)發(fā)送郵件任務(wù)
這篇文章主要為大家詳細(xì)介紹了SpringBoot實(shí)現(xiàn)發(fā)送郵件任務(wù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02
Spring整合MyBatis(Maven+MySQL)圖文教程詳解
這篇文章主要介紹了Spring整合MyBatis(Maven+MySQL)圖文教程詳解的相關(guān)資料,需要的朋友可以參考下2016-07-07
springBoot?之spring.factories擴(kuò)展機(jī)制示例解析
這篇文章主要為大家介紹了springBoot?之spring.factories擴(kuò)展機(jī)制示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

