首先新建一個(gè)簡單的數(shù)據(jù)表,通過操作這個(gè)數(shù)據(jù)表來進(jìn)行演示
1
2
3
4
5
6
7
8
|
DROP TABLE IF EXISTS `items`; CREATE TABLE `items` ( `id` int ( 11 ) NOT NULL AUTO_INCREMENT, `title` varchar( 255 ) DEFAULT NULL, `name` varchar( 10 ) DEFAULT NULL, `detail` varchar( 255 ) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT= 7 DEFAULT CHARSET=utf8; |
引入JdbcTemplate的maven依賴及連接類
1
2
3
4
5
6
7
8
9
|
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> |
在application.properties文件配置mysql的驅(qū)動(dòng)類,數(shù)據(jù)庫地址,數(shù)據(jù)庫賬號(hào)、密碼信息,application.properties新建在src/main/resource文件夾下
1
2
3
4
5
6
7
8
9
10
11
|
spring.datasource.url=jdbc:mysql: //127.0.0.1:3306/spring?useSSL=false spring.datasource.username=root spring.datasource.password= 123456 spring.datasource.driver- class -name=com.mysql.jdbc.Driver spring.datasource.max-idle= 10 spring.datasource.max-wait= 10000 spring.datasource.min-idle= 5 spring.datasource.initial-size= 5 server.port= 8080 server.session.timeout= 10 server.tomcat.uri-encoding=UTF- 8 |
新建一個(gè)實(shí)體類,屬性對(duì)應(yīng)sql字段
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
|
package org.amuxia.start; public class Items { private Integer id; private String title; private String name; private String detail; public Integer getId() { return id; } public void setId(Integer id) { this .id = id; } public String getTitle() { return title; } public void setTitle(String title) { this .title = title; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getDetail() { return detail; } public void setDetail(String detail) { this .detail = detail; } public Items() { super (); // TODO Auto-generated constructor stub } public Items(Integer id, String title, String name, String detail) { super (); this .id = id; this .title = title; this .name = name; this .detail = detail; } @Override public String toString() { return "Items [id=" + id + ", id="codetool">
新增操作
我們做一個(gè)測試。在postman測試工具中輸入http://localhost:8080/items/add
我們可以看到,新增已經(jīng)成功了,確實(shí)很方便,也沒有繁瑣的配置信息。 其余刪除,更新操作與新增代碼不變,只是sql的變化,這里不做演示。 全部查詢操作
我們做一個(gè)測試。在postman測試工具中輸入http://localhost:8080/items/list 我們看到,包括剛才新增的數(shù)據(jù),都已經(jīng)被查出來了。
這里為了學(xué)習(xí)一下springboot的JdbcTemplate操作,所有增刪改查代碼都寫在ItemsController類中,也方便演示,這里把代碼貼出來,需要的可以運(yùn)行一下
|