一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Spring JdbcTemplate整合使用方法及原理詳解

Spring JdbcTemplate整合使用方法及原理詳解

2020-08-17 14:22柒丶月 Java教程

這篇文章主要介紹了Spring JdbcTemplate整合使用方法及原理詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

基本配置

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

Spring JdbcTemplate整合使用方法及原理詳解

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<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>

項目創(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了?咋這么方便呢?其實這就是SpringBoot的自動化配置帶來的好處,我們先說用法,一會來說原理。

基本用法

首先我們來創(chuàng)建一個User Bean,如下:

?
1
2
3
4
5
6
public class User {
  private Long id;
  private String username;
  private String address;
  //省略getter/setter
}

然后來創(chuàng)建一個UserService類,在UserService類中注入JdbcTemplate,如下:

?
1
2
3
4
5
@Service
public class UserService {
  @Autowired
  JdbcTemplate jdbcTemplate;
}

好了,如此之后,準(zhǔn)備工作就算完成了。

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

?
1
2
3
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ù)插入的過程中希望實現(xiàn)主鍵回填,那么可以使用PreparedStatementCreator,如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}

實際上這里就相當(dāng)于完全使用了JDBC中的解決方案了,首先在構(gòu)建PreparedStatement時傳入Statement.RETURN_GENERATED_KEYS,然后傳入KeyHolder,最終從KeyHolder中獲取剛剛插入數(shù)據(jù)的id保存到user對象的id屬性中去。

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

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

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

當(dāng)然你也可以使用PreparedStatementCreator。

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

當(dāng)然你也可以使用PreparedStatementCreator。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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,就是需要自己手動映射,將數(shù)據(jù)庫中的字段和對象的屬性一一對應(yīng)起來,這樣。。。。嗯看起來有點麻煩,實際上,如果數(shù)據(jù)庫中的字段和對象屬性的名字一模一樣的話,有另外一個簡單的方案,如下:

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

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

其他

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

原理分析

那么在SpringBoot中,配置完數(shù)據(jù)庫基本信息之后,就有了一個JdbcTemplate了,這個東西是從哪里來的呢?源碼在

org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration類中,該類源碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@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);
    }
}
}

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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:https://www.cnblogs.com/qiuwenli/p/13442741.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 波多野结衣无码 | 国产免费一区二区 | 视频在线观看高清免费 | 久久亚洲精品成人 | 亚洲AV永久无码精品澳门 | 日本熟hdx | 百合漫画咱啪全彩抚慰 | 我半夜摸妺妺的奶C了她 | 亚洲AV精品无码喷水直播间 | 糖心在线观看网 | 亚洲男人的天堂网 | 国产精品亚洲精品青青青 | 91久久国产视频 | 成人国产在线观看 | 黑帮大佬与我的365天2标清中文 | 国产午夜精品久久久久小说 | 午夜桃色剧场 | 顶级尤物极品女神福利视频 | 被夫上司强迫中文 | 色偷偷伊人 | 天美传媒影视在线免费观看 | 超91精品手机国产在线 | 美女被吸乳得到大胸 | 牧教师| 国产va欧美va在线观看 | 亚洲精品在线免费 | mm在线| 亚洲性视频在线观看 | 日本ww视频| 国人精品视频在线观看 | 国产成人盗摄精品 | 久久久GOGO无码啪啪艺术 | 美女福利视频午夜在线 | 日本在线看| 我将她侵犯1~6樱花动漫在线看 | 亚洲视频一区网站 | 精品国产一级毛片大全 | 偷偷狠狠的日日高清完整视频 | 日韩精品视频在线观看免费 | 精品国产福利在线观看一区 | 亚洲国产在 |