使用JdbcTemplate訪問數據庫

SpringBoot 是爲了簡化 Spring 應用的建立、運行、調試、部署等一系列問題而誕生的產物,自動裝配的特性讓咱們能夠更好的關注業務自己而不是外部的XML配置,咱們只需遵循規範,引入相關的依賴就能夠輕易的搭建出一個 WEB 工程html

Spring Framework對數據庫的操做在JDBC上面作了深層次的封裝,經過依賴注入功能,能夠將 DataSource 註冊到JdbcTemplate之中,使咱們能夠輕易的完成對象關係映射,並有助於規避常見的錯誤,在SpringBoot中咱們能夠很輕鬆的使用它。java

特色mysql

  • 速度快,對比其它的ORM框架而言,JDBC的方式無異因而最快的
  • 配置簡單,Spring自家出品,幾乎沒有額外配置
  • 學習成本低,畢竟JDBC是基礎知識,JdbcTemplate更像是一個DBUtils

導入依賴

在 pom.xml 中添加對 JdbcTemplate 的依賴web

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- Spring JDBC 的依賴包,使用 spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa 將會自動得到HikariCP依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MYSQL包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 默認就內嵌了Tomcat 容器,如須要更換容器也極其簡單-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

鏈接數據庫

application.properties中添加以下配置。值得注意的是,SpringBoot默認會自動配置DataSource,它將優先採用HikariCP鏈接池,若是沒有該依賴的狀況則選取tomcat-jdbc,若是前二者都不可用最後選取Commons DBCP2經過spring.datasource.type屬性能夠指定其它種類的鏈接池spring

1
2
3
4
5
6
7
8
spring.datasource.url=jdbc:mysql://localhost:3306/chapter4?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.password=root
spring.datasource.username=root
#spring.datasource.type
#更多細微的配置能夠經過下列前綴進行調整
#spring.datasource.hikari
#spring.datasource.tomcat
#spring.datasource.dbcp2

啓動項目,經過日誌,能夠看到默認狀況下注入的是HikariDataSourcesql

1
2
3
4
2018-05-07 10:33:54.021 INFO 9640 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-05-07 10:33:54.026 INFO 9640 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-05-07 10:33:54.071 INFO 9640 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-05-07 10:33:54.075 INFO 9640 --- [ main] com.battcn.Chapter4Application : Started Chapter4Application in 3.402 seconds (JVM running for 3.93)

具體編碼

完成基本配置後,接下來進行具體的編碼操做。爲了減小代碼量,就不寫UserDaoUserService之類的接口了,將直接在Controller中使用JdbcTemplate進行訪問數據庫操做,這點是不規範的,各位別學我…數據庫

表結構

建立一張 t_user 的表api

1
2
3
4
5
6
CREATE TABLE `t_user` (
`id` int(8) NOT NULL AUTO_INCREMENT COMMENT '主鍵自增',
`username` varchar(50) NOT NULL COMMENT '用戶名',
`password` varchar(50) NOT NULL COMMENT '密碼',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用戶表';

實體類

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.battcn.entity;

/**
* @author Levin
* @since 2018/5/7 0007
*/
public class User {

private Long id;
private String username;
private String password;
// TODO 省略get set
}

restful 風格接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.battcn.controller;

import com.battcn.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
* @author Levin
* @since 2018/4/23 0023
*/
@RestController
@RequestMapping("/users")
public class SpringJdbcController {

private final JdbcTemplate jdbcTemplate;

@Autowired
public SpringJdbcController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

@GetMapping
public List<User> queryUsers() {
// 查詢全部用戶
String sql = "select * from t_user";
return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(User.class));
}

@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// 根據主鍵ID查詢
String sql = "select * from t_user where id = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
}

@DeleteMapping("/{id}")
public int delUser(@PathVariable Long id) {
// 根據主鍵ID刪除用戶信息
String sql = "DELETE FROM t_user WHERE id = ?";
return jdbcTemplate.update(sql, id);
}

@PostMapping
public int addUser(@RequestBody User user) {
// 添加用戶
String sql = "insert into t_user(username, password) values(?, ?)";
return jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
}


@PutMapping("/{id}")
public int editUser(@PathVariable Long id, @RequestBody User user) {
// 根據主鍵ID修改用戶信息
String sql = "UPDATE t_user SET username = ? ,password = ? WHERE id = ?";
return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), id);
}
}

測試

因爲上面的接口是 restful 風格的接口,添加和修改沒法經過瀏覽器完成,因此須要咱們本身編寫junit或者使用postman之類的工具。瀏覽器

建立單元測試Chapter4ApplicationTests,經過TestRestTemplate模擬GETPOSTPUTDELETE等請求操做tomcat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.battcn;

import com.battcn.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
* @author Levin
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Chapter4Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Chapter4ApplicationTests {

private static final Logger log = LoggerFactory.getLogger(Chapter4ApplicationTests.class);
@Autowired
private TestRestTemplate template;
@LocalServerPort
private int port;

@Test
public void test1() throws Exception {
template.postForEntity("http://localhost:" + port + "/users", new User("user1", "pass1"), Integer.class);
log.info("[添加用戶成功]\n");
// TODO 若是是返回的集合,要用 exchange 而不是 getForEntity ,後者須要本身強轉類型
ResponseEntity<List<User>> response2 = template.exchange("http://localhost:" + port + "/users", HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>() {
});
final List<User> body = response2.getBody();
log.info("[查詢全部] - [{}]\n", body);
Long userId = body.get(0).getId();
ResponseEntity<User> response3 = template.getForEntity("http://localhost:" + port + "/users/{id}", User.class, userId);
log.info("[主鍵查詢] - [{}]\n", response3.getBody());
template.put("http://localhost:" + port + "/users/{id}", new User("user11", "pass11"), userId);
log.info("[修改用戶成功]\n");
template.delete("http://localhost:" + port + "/users/{id}", userId);
log.info("[刪除用戶成功]");
}
}

總結

本章介紹了JdbcTemplate經常使用的幾種操做,詳細請參考JdbcTemplate API文檔

相關文章
相關標籤/搜索