天天看點

Spring Boot 中使用 Jdbc Template 通路資料庫

之前介紹了很多Web層的例子,包括建構、,但是這些内容還不足以建構一個動态的應用。通常我們做App也好,做Web應用也好,都需要内容,而内容通常存儲于各種類型的資料庫,服務端在接收到通路請求之後需要通路資料庫擷取并處理成展現給使用者使用的資料形式。

嵌入式資料庫支援

嵌入式資料庫通常用于開發和測試環境,不推薦用于生産環境。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>

<version>5.1.21</version>

</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.jdbc.Driver

連接配接JNDI資料源

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

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

使用JdbcTemplate操作資料庫

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

舉例:我們在建立User表,包含屬性name、age,下面來編寫資料通路對象和單元測試用例。

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

public interface UserService {

void create(String name, Integer age);

void deleteByName(String name);

Integer getAllUsers();

void deleteAllUsers();

}

通過JdbcTemplate實作UserService中定義的資料通路操作

@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("delete from USER");

}

}

建立對UserService的單元測試用例,通過建立、删除和查詢來驗證資料庫操作的正确性。

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(Application.class)

public class ApplicationTests {

@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());

}

}

上面介紹的JdbcTemplate隻是最基本的幾個操作,更多其他資料通路操作的使用請參考:JdbcTemplate API(https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html)。

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