Spring Boot數據持久化之JdbcTemplate

在Java領域,數據持久化有幾個常見的方案,有Spring自帶的JdbcTemplate、有MyBatis,還有JPA,在這些方案中,最簡單的就是Spring自帶的JdbcTemplate了,這個東西雖然沒有MyBatis那麼方便,可是比起最開始的Jdbc已經強了不少了,它沒有MyBatis功能那麼強大,固然也意味着它的使用比較簡單,事實上,JdbcTemplate算是最簡單的數據持久化方案了,本文就和大夥來講說這個東西的使用。java

基本配置

JdbcTemplate基本用法實際上很簡單,開發者在建立一個SpringBoot項目時,除了選擇基本的Web依賴,再記得選上Jdbc依賴,以及數據庫驅動依賴便可,以下: mysql

圖片描述

項目建立成功以後,記得添加Druid數據庫鏈接池依賴(注意這裏能夠添加專門爲Spring Boot打造的druid-spring-boot-starter,而不是咱們通常在SSM中添加的Druid),全部添加的依賴以下:web

<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

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的自動化配置帶來的好處,咱們先說用法,一會來講原理。sql

基本用法

首先咱們來建立一個User Bean,以下:數據庫

public class User {
    private Long id;
    private String username;
    private String address;
    //省略getter/setter
}

而後來建立一個UserService類,在UserService類中注入JdbcTemplate,以下:後端

@Service
public class UserService {
    @Autowired
    JdbcTemplate jdbcTemplate;
}

好了,如此以後,準備工做就算完成了。app

JdbcTemplate中,除了查詢有幾個API以外,增刪改統一都使用update來操做,本身來傳入SQL便可。例如添加數據,方法以下:前後端分離

public int addUser(User user) {
    return jdbcTemplate.update("insert into user (username,address) values (?,?);", user.getUsername(), user.getAddress());
}

update方法的返回值就是SQL執行受影響的行數。 ide

這裏只須要傳入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接口的一個實現)。好了,不知道大夥有沒有收穫呢?

關於JdbcTemplate,我還有一個小小視頻,加入個人知識星球,免費觀看:

圖片描述

加入個人星球,和衆多大牛一塊兒切磋技術推薦一個技術圈子,Java技能提高就靠它了

圖片描述
關注公衆號【江南一點雨】,專一於 Spring Boot+微服務以及先後端分離等全棧技術,按期視頻教程分享,關注後回覆 Java ,領取鬆哥爲你精心準備的 Java 乾貨!

相關文章
相關標籤/搜索