您好,登錄后才能下訂單哦!
這篇文章主要介紹了Spring JdbcTemplate整合的使用方法是什么,具有一定借鑒價(jià)值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
基本配置
JdbcTemplate基本用法實(shí)際上很簡(jiǎn)單,開(kāi)發(fā)者在創(chuàng)建一個(gè)SpringBoot項(xiàng)目時(shí),除了選擇基本的Web依賴(lài),再記得選上Jdbc依賴(lài),以及數(shù)據(jù)庫(kù)驅(qū)動(dòng)依賴(lài)即可,如下:
項(xiàng)目創(chuàng)建成功之后,記得添加Druid數(shù)據(jù)庫(kù)連接池依賴(lài)(注意這里可以添加專(zhuān)門(mén)為Spring Boot打造的druid-spring-boot-starter,而不是我們一般在SSM中添加的Druid),所有添加的依賴(lài)如下:
<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.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.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類(lèi),在UserService類(lèi)中注入JdbcTemplate,如下:
@Service public class UserService { @Autowired JdbcTemplate jdbcTemplate; }
好了,如此之后,準(zhǔn)備工作就算完成了。
增
JdbcTemplate中,除了查詢(xún)有幾個(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。
查
查詢(xún)的話(huà),稍微有點(diǎn)變化,這里主要向大伙介紹query方法,例如查詢(xún)所有用戶(hù):
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; } }); }
查詢(xún)的時(shí)候需要提供一個(gè)RowMapper,就是需要自己手動(dòng)映射,將數(shù)據(jù)庫(kù)中的字段和對(duì)象的屬性一一對(duì)應(yīng)起來(lái),這樣。。。。嗯看起來(lái)有點(diǎn)麻煩,實(shí)際上,如果數(shù)據(jù)庫(kù)中的字段和對(duì)象屬性的名字一模一樣的話(huà),有另外一個(gè)簡(jiǎn)單的方案,如下:
public List<User> getAllUsers2() { return jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class)); }
至于查詢(xún)時(shí)候傳參也是使用占位符,這個(gè)和前文的一致,這里不再贅述。
其他
除了這些基本用法之外,JdbcTemplate也支持其他用法,例如調(diào)用存儲(chǔ)過(guò)程等,這些都比較容易,而且和Jdbc本身都比較相似,這里也就不做介紹了,有興趣可以留言討論。
原理分析
那么在SpringBoot中,配置完數(shù)據(jù)庫(kù)基本信息之后,就有了一個(gè)JdbcTemplate了,這個(gè)東西是從哪里來(lái)的呢?源碼在
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration類(lèi)中,該類(lèi)源碼如下:
@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è)類(lèi)中,大致可以看出,當(dāng)當(dāng)前類(lèi)路徑下存在DataSource和JdbcTemplate時(shí),該類(lèi)就會(huì)被自動(dòng)配置,jdbcTemplate方法則表示,如果開(kāi)發(fā)者沒(méi)有自己提供一個(gè)JdbcOperations的實(shí)例的話(huà),系統(tǒng)就自動(dòng)配置一個(gè)JdbcTemplate Bean(JdbcTemplate是JdbcOperations接口的一個(gè)實(shí)現(xiàn))。好了,不知道大伙有沒(méi)有收獲呢?
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享Spring JdbcTemplate整合的使用方法是什么內(nèi)容對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問(wèn)題就找億速云,詳細(xì)的解決方法等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。