Spring Boot 2.x基礎(chǔ)教程:使用JdbcTemplate訪問MySQL數(shù)據(jù)庫

在第2章節(jié)中,我們介紹了如何通過Spring Boot來實現(xiàn)HTTP接口,以及圍繞HTTP接口相關(guān)的單元測試、文檔生成等實用技能。但是,這些內(nèi)容還不足以幫助我們構(gòu)建一個動態(tài)應(yīng)用的服務(wù)端程序。不論我們是要做App、小程序、還是傳統(tǒng)的Web站點,對于用戶的信息、相關(guān)業(yè)務(wù)的內(nèi)容,通常都需要對其進行存儲,而不是像第2章節(jié)中那樣,把用戶信息存儲在內(nèi)存中(重啟就丟了?。?。

對于信息的存儲,現(xiàn)在已經(jīng)有非常非常多的產(chǎn)品可以選擇,其中不乏許多非常優(yōu)秀的開源免費產(chǎn)品,比如:MySQL,Redis等。接下來,在第3章節(jié),我們將繼續(xù)學(xué)習(xí)在使用Spring Boot開發(fā)服務(wù)端程序的時候,如何實現(xiàn)對各流行數(shù)據(jù)存儲產(chǎn)品的增刪改查操作。

作為數(shù)據(jù)訪問章節(jié)的第一篇,我們將從最為常用的關(guān)系型數(shù)據(jù)庫開始。通過一個簡單例子,學(xué)習(xí)在Spring Boot中最基本的數(shù)據(jù)訪問工具:JdbcTemplate。

數(shù)據(jù)源配置

在我們訪問數(shù)據(jù)庫的時候,需要先配置一個數(shù)據(jù)源,下面分別介紹一下幾種不同的數(shù)據(jù)庫配置方式。

首先,為了連接數(shù)據(jù)庫需要引入jdbc支持,在pom.xml中引入如下配置:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

嵌入式數(shù)據(jù)庫支持

嵌入式數(shù)據(jù)庫通常用于開發(fā)和測試環(huán)境,不推薦用于生產(chǎn)環(huán)境。Spring Boot提供自動配置的嵌入式數(shù)據(jù)庫有H2、HSQL、Derby,你不需要提供任何連接配置就能使用。

比如,我們可以在pom.xml中引入如下配置使用HSQL

<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

連接生產(chǎn)數(shù)據(jù)源

以MySQL數(shù)據(jù)庫為例,先引入MySQL連接的依賴包,在pom.xml中加入:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.46</version>
</dependency>

src/main/resources/application.properties中配置數(shù)據(jù)源信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

連接JNDI數(shù)據(jù)源

當(dāng)你將應(yīng)用部署于應(yīng)用服務(wù)器上的時候想讓數(shù)據(jù)源由應(yīng)用服務(wù)器管理,那么可以使用如下配置方式引入JNDI數(shù)據(jù)源。

spring.datasource.jndi-name=java:jboss/datasources/customers

使用JdbcTemplate操作數(shù)據(jù)庫

Spring的JdbcTemplate是自動配置的,你可以直接使用@Autowired或構(gòu)造函數(shù)(推薦)來注入到你自己的bean中來使用。

下面就來一起完成一個增刪改查的例子:

準(zhǔn)備數(shù)據(jù)庫

先創(chuàng)建User表,包含屬性name、age??梢酝ㄟ^執(zhí)行下面的建表語句::

CREATE TABLE `User` (
  `name` varchar(100) COLLATE utf8mb4_general_ci NOT NULL,
  `age` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

編寫領(lǐng)域?qū)ο?/h4>

根據(jù)數(shù)據(jù)庫中創(chuàng)建的User表,創(chuàng)建領(lǐng)域?qū)ο螅?/p>

@Data
@NoArgsConstructor
public class User {

    private String name;
    private Integer age;

}

這里使用了Lombok的@Data@NoArgsConstructor注解來自動生成各參數(shù)的Set、Get函數(shù)以及不帶參數(shù)的構(gòu)造函數(shù)。如果您對Lombok還不了解,可以看看這篇文章:Java開發(fā)神器Lombok的使用與原理

編寫數(shù)據(jù)訪問對象

  • 定義包含有插入、刪除、查詢的抽象接口UserService
public interface UserService {

    /**
     * 新增一個用戶
     *
     * @param name
     * @param age
     */
    int create(String name, Integer age);

    /**
     * 根據(jù)name查詢用戶
     *
     * @param name
     * @return
     */
    List<User> getByName(String name);

    /**
     * 根據(jù)name刪除用戶
     *
     * @param name
     */
    int deleteByName(String name);

    /**
     * 獲取用戶總量
     */
    int getAllUsers();

    /**
     * 刪除所有用戶
     */
    int deleteAllUsers();

}
  • 通過JdbcTemplate實現(xiàn)UserService中定義的數(shù)據(jù)訪問操作
@Service
public class UserServiceImpl implements UserService {

    private JdbcTemplate jdbcTemplate;

    UserServiceImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int create(String name, Integer age) {
        return jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age);
    }

    @Override
    public List<User> getByName(String name) {
        List<User> users = jdbcTemplate.query("select NAME, AGE from USER where NAME = ?", (resultSet, i) -> {
            User user = new User();
            user.setName(resultSet.getString("NAME"));
            user.setAge(resultSet.getInt("AGE"));
            return user;
        }, name);
        return users;
    }

    @Override
    public int deleteByName(String name) {
        return jdbcTemplate.update("delete from USER where NAME = ?", name);
    }

    @Override
    public int getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
    }

    @Override
    public int deleteAllUsers() {
        return jdbcTemplate.update("delete from USER");
    }

}

編寫單元測試用例

  • 創(chuàng)建對UserService的單元測試用例,通過創(chuàng)建、刪除和查詢來驗證數(shù)據(jù)庫操作的正確性。
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter31ApplicationTests {

    @Autowired
    private UserService userSerivce;

    @Before
    public void setUp() {
        // 準(zhǔn)備,清空user表
        userSerivce.deleteAllUsers();
    }

    @Test
    public void test() throws Exception {
        // 插入5個用戶
        userSerivce.create("Tom", 10);
        userSerivce.create("Mike", 11);
        userSerivce.create("Didispace", 30);
        userSerivce.create("Oscar", 21);
        userSerivce.create("Linda", 17);

        // 查詢名為Oscar的用戶,判斷年齡是否匹配
        List<User> userList = userSerivce.getByName("Oscar");
        Assert.assertEquals(21, userList.get(0).getAge().intValue());

        // 查數(shù)據(jù)庫,應(yīng)該有5個用戶
        Assert.assertEquals(5, userSerivce.getAllUsers());

        // 刪除兩個用戶
        userSerivce.deleteByName("Tom");
        userSerivce.deleteByName("Mike");

        // 查數(shù)據(jù)庫,應(yīng)該有5個用戶
        Assert.assertEquals(3, userSerivce.getAllUsers());

    }

}

上面介紹的JdbcTemplate只是最基本的幾個操作,更多其他數(shù)據(jù)訪問操作的使用請參考:JdbcTemplate API

通過上面這個簡單的例子,我們可以看到在Spring Boot下訪問數(shù)據(jù)庫的配置依然秉承了框架的初衷:簡單。我們只需要在pom.xml中加入數(shù)據(jù)庫依賴,再到application.properties中配置連接信息,不需要像Spring應(yīng)用中創(chuàng)建JdbcTemplate的Bean,就可以直接在自己的對象中注入使用。

代碼示例

本文的相關(guān)例子可以查看下面?zhèn)}庫中的chapter3-1目錄:

如果您覺得本文不錯,歡迎Star支持,您的關(guān)注是我堅持的動力!

歡迎關(guān)注我的公眾號:程序猿DD,獲得獨家整理的學(xué)習(xí)資源和日常干貨推送。
如果您對我的專題內(nèi)容感興趣,也可以關(guān)注我的博客:didispace.com

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容