Spring Boot中使用JdbcTemplate訪問數據庫

之前介紹了很多Web層的例子,包括構建RESTful API、使用Thymeleaf模板引擎渲染Web視圖,但是這些內容還不足以構建一個動態的應用。通常我們做App也好,做Web應用也好,都需要內容,而內容通常存儲於各種類型的數據庫,服務端在接收到訪問請求之後需要訪問數據庫獲取並處理成展現給用戶使用的數據形式。

本文介紹在Spring Boot基礎下配置數據源和通過JdbcTemplate編寫數據訪問的示例。

數據源配置

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

首先,爲了連接數據庫需要引入jdbc支持,在pom.xml中引入如下配置:
{% highlight null %}

org.springframework.boot
spring-boot-starter-jdbc

{% endhighlight %}

嵌入式數據庫支持

(不需要使用)

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

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

org.hsqldb
hsqldb
runtime

{% endhighlight %}

連接生產數據源

以MySQL數據庫爲例,先引入MySQL連接的依賴包,在pom.xml中加入:

{% highlight null %}

mysql
mysql-connector-java
runtime

{% endhighlight %}

在src/main/resources/application.properties中配置數據源信息

{% highlight null %}
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
{% endhighlight %}

可以使用application.yml進行配置,代碼如下:

{% highlight null %}
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&autoReconnectForPools=true
username: root
password: 1234567890
tomcat:
max-active: 100
initial-size: 5
max-idle: 10
min-idle: 5
test-while-idle: true
test-on-borrow: true
validation-query: SELECT 1
time-between-eviction-runs-millis: 5000
min-evictable-idle-time-millis: 60000
{% endhighlight %}

連接JNDI數據源

當你將應用部署於應用服務器上的時候想讓數據源由應用服務器管理,那麼可以使用如下配置方式引入JNDI數據源。

{% highlight null %}

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

{% endhighlight %}

使用JdbcTemplate操作數據庫

Spring的JdbcTemplate是自動配置的,你可以直接使用@Autowired來注入到你自己的bean中來使用。

舉例:我們在創建User表,包含屬性name、age,下面來編寫數據訪問對象和單元測試用例。

定義包含有插入、刪除、查詢的抽象接口UserService
{% highlight java %}
package com.xuying.demo.service;

public interface UserService {
/**
* 新增一個用戶
*
* @param name
* @param age
*/
void create(String name, Integer age);

/**
 * 根據name刪除一個用戶高
 * 
 * @param name
 */
void deleteByName(String name);

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

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

}
{% endhighlight %}

通過JdbcTemplate實現UserService中定義的數據訪問操作

{% highlight java %}
package com.xuying.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;

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

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

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

@Override
public void deleteAllUsers() {
    jdbcTemplate.update("TRUNCATE table USER");
}

}

{% endhighlight %}

創建對UserService的單元測試用例,通過創建、刪除和查詢來驗證數據庫操作的正確性。

{% highlight java %}
package com.xuying;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.xuying.demo.DemoApplication;
import com.xuying.demo.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest
@SpringApplicationConfiguration(DemoApplication.class)
public class ApplicationTestsJdbc {
@Autowired
private UserService userSerivce;

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

@Test
public void test() throws Exception {
    // 插入5個用戶
    userSerivce.create("a", 1);
    userSerivce.create("b", 2);
    userSerivce.create("c", 3);
    userSerivce.create("d", 4);
    userSerivce.create("e", 5);
    // 查數據庫,應該有5個用戶
    Assert.assertEquals(5, userSerivce.getAllUsers().intValue());
    // 刪除兩個用戶
    userSerivce.deleteByName("a");
    userSerivce.deleteByName("e");
    // 查數據庫,應該有5個用戶
    Assert.assertEquals(3, userSerivce.getAllUsers().intValue());
}

}
{% endhighlight %}

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

發佈了27 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章