天天看點

Spring Boot 2.x基礎教程:使用JdbcTemplate通路MySQL資料庫

在第2章節中,我們介紹了如何通過Spring Boot來實作HTTP接口,以及圍繞HTTP接口相關的單元測試、文檔生成等實用技能。但是,這些内容還不足以幫助我們建構一個動态應用的服務端程式。不論我們是要做App、小程式、還是傳統的Web站點,對于使用者的資訊、相關業務的内容,通常都需要對其進行存儲,而不是像第2章節中那樣,把使用者資訊存儲在記憶體中(重新開機就丢了!)。

對于資訊的存儲,現在已經有非常非常多的産品可以選擇,其中不乏許多非常優秀的開源免費産品,比如:MySQL,Redis等。接下來,在第3章節,我們将繼續學習在使用Spring Boot開發服務端程式的時候,如何實作對各流行資料存儲産品的增删改查操作。

作為資料通路章節的第一篇,我們将從最為常用的關系型資料庫開始。通過一個簡單例子,學習在Spring Boot中最基本的資料通路工具:JdbcTemplate。

https://blog.didispace.com/spring-boot-learning-21-3-1/#%E6%95%B0%E6%8D%AE%E6%BA%90%E9%85%8D%E7%BD%AE 資料源配置

在我們通路資料庫的時候,需要先配置一個資料源,下面分别介紹一下幾種不同的資料庫配置方式。

首先,為了連接配接資料庫需要引入jdbc支援,在

pom.xml

中引入如下配置:

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

嵌入式資料庫支援

嵌入式資料庫通常用于開發和測試環境,不推薦用于生産環境。Spring Boot提供自動配置的嵌入式資料庫有H2、HSQL、Derby,你不需要提供任何連接配接配置就能使用。

比如,我們可以在

pom.xml

中引入如下配置使用HSQL

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

連接配接生産資料源

以MySQL資料庫為例,先引入MySQL連接配接的依賴包,在

pom.xml

中加入:

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

src/main/resources/application.properties

中配置資料源資訊

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

注意:因為Spring Boot 2.1.x預設使用了MySQL 8.0的驅動,是以這裡采用

com.mysql.cj.jdbc.Driver

,而不是老的

com.mysql.jdbc.Driver

https://blog.didispace.com/spring-boot-learning-21-3-1/#%E8%BF%9E%E6%8E%A5JNDI%E6%95%B0%E6%8D%AE%E6%BA%90 連接配接JNDI資料源

當你将應用部署于應用伺服器上的時候想讓資料源由應用伺服器管理,那麼可以使用如下配置方式引入JNDI資料源。

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

使用JdbcTemplate操作資料庫

Spring的JdbcTemplate是自動配置的,你可以直接使用

@Autowired

或構造函數(推薦)來注入到你自己的bean中來使用。

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

https://blog.didispace.com/spring-boot-learning-21-3-1/#%E5%87%86%E5%A4%87%E6%95%B0%E6%8D%AE%E5%BA%93 準備資料庫

先建立

User

表,包含屬性

name

age

。可以通過執行下面的建表語句::

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      

編寫領域對象

根據資料庫中建立的

User

表,建立領域對象:

@Data
@NoArgsConstructor
public class User {

    private String name;
    private Integer age;

}      

這裡使用了Lombok的

@Data

@NoArgsConstructor

注解來自動生成各參數的Set、Get函數以及不帶參數的構造函數。如果您對Lombok還不了解,可以看看這篇文章:

Java開發神器Lombok的使用與原理

https://blog.didispace.com/spring-boot-learning-21-3-1/#%E7%BC%96%E5%86%99%E6%95%B0%E6%8D%AE%E8%AE%BF%E9%97%AE%E5%AF%B9%E8%B1%A1 編寫資料通路對象

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

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

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

    /**
     * 根據name删除使用者
     *
     * @param name
     */
    int deleteByName(String name);

    /**
     * 擷取使用者總量
     */
    int getAllUsers();

    /**
     * 删除所有使用者
     */
    int deleteAllUsers();

}      
  • 通過

    JdbcTemplate

    實作

    UserService

    中定義的資料通路操作
@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");
    }      

編寫單元測試用例

  • 建立對UserService的單元測試用例,通過建立、删除和查詢來驗證資料庫操作的正确性。
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter31ApplicationTests {

    @Autowired
    private UserService userSerivce;

    @Before
    public void setUp() {
        // 準備,清空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());

        // 查資料庫,應該有5個使用者
        Assert.assertEquals(5, userSerivce.getAllUsers());

        // 删除兩個使用者
        userSerivce.deleteByName("Tom");
        userSerivce.deleteByName("Mike");

        // 查資料庫,應該有5個使用者
        Assert.assertEquals(3, userSerivce.getAllUsers());

    }

}      

上面介紹的

JdbcTemplate

隻是最基本的幾個操作,更多其他資料通路操作的使用請參考​:

JdbcTemplate API

通過上面這個簡單的例子,我們可以看到在Spring Boot下通路資料庫的配置依然秉承了架構的初衷:簡單。我們隻需要在pom.xml中加入資料庫依賴,再到application.properties中配置連接配接資訊,不需要像Spring應用中建立JdbcTemplate的Bean,就可以直接在自己的對象中注入使用。

本系列教程

《Spring Boot 2.x基礎教程》點選直達!

。學習過程中如遇困難,建議加入

Spring技術交流群

,參與交流與讨論,更好的學習與進步!

https://blog.didispace.com/spring-boot-learning-21-3-1/#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B 代碼示例

本文的相關例子可以檢視下面倉庫中的

chapter3-1

目錄: