本文是對SpringBoot使用JdbcTemplate操做數據庫的一個介紹,,提供一個小的Demo供你們參考。html
操做數據庫的方式有不少,本文介紹使用SpringBoot結合JdbcTemplate。java
新建一個項目。pom文件中加入Jdbc依賴,完整pom以下:mysql
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalaoyang</groupId>
<artifactId>springboot_jdbc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_jdbc</name>
<description>springboot_jdbc</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
複製代碼
配置文件以下:git
##端口號
server.port=8888
##數據庫配置
##數據庫地址
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##數據庫用戶名
spring.datasource.username=root
##數據庫密碼
spring.datasource.password=123456
##數據庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
複製代碼
新建一個實體類User,其中須要注意的是,User類實現了RowMapper類,重寫了mapRow方法,完整代碼以下:web
package com.dalaoyang.entity;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author dalaoyang
* @project springboot_learn
* @package com.dalaoyang.entity
* @email yangyang@dalaoyang.cn
* @date 2018/7/25
*/
public class User implements RowMapper<User> {
private int id;
private String user_name;
private String pass_word;
public User(int id, String user_name, String pass_word) {
this.id = id;
this.user_name = user_name;
this.pass_word = pass_word;
}
public User() {
}
public User(String user_name, String pass_word) {
this.user_name = user_name;
this.pass_word = pass_word;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPass_word() {
return pass_word;
}
public void setPass_word(String pass_word) {
this.pass_word = pass_word;
}
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUser_name(resultSet.getString("user_name"));
user.setPass_word(resultSet.getString("pass_word"));
return user;
}
}
複製代碼
經常使用CURD操做大體使用如下三個方法:
1.execute方法,用於直接執行SQL語句
2.update方法,用戶新增修改刪除操做
3.query方法,用於查詢方法spring
本文和往常同樣,用Controller進行測試,注入JdbcTemplate。完整代碼以下,下面會對測試方法進行介紹:sql
package com.dalaoyang.controller;
import com.dalaoyang.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author dalaoyang
* @project springboot_learn
* @package com.dalaoyang.controller
* @email yangyang@dalaoyang.cn
* @date 2018/7/25
*/
@RestController
public class UserController {
@Autowired
private JdbcTemplate jdbcTemplate;
//http://localhost:8888/createTable
@GetMapping("createTable")
public String createTable(){
String sql = "CREATE TABLE `user` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `user_name` varchar(255) DEFAULT NULL,\n" +
" `pass_word` varchar(255) DEFAULT NULL,\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;\n" +
"\n";
jdbcTemplate.execute(sql);
return "建立User表成功";
}
//http://localhost:8888/saveUserSql
@GetMapping("saveUserSql")
public String saveUserSql(){
String sql = "INSERT INTO USER (USER_NAME,PASS_WORD) VALUES ('dalaoyang','123')";
int rows= jdbcTemplate.update(sql);
return "執行成功,影響"+rows+"行";
}
//http://localhost:8888/saveUser?userName=lisi&passWord=111
@GetMapping("saveUser")
public String saveUser(String userName,String passWord){
int rows= jdbcTemplate.update("INSERT INTO USER (USER_NAME,PASS_WORD) VALUES (?,?)",userName,passWord);
return "執行成功,影響"+rows+"行";
}
//http://localhost:8888/updateUserPassword?id=1&passWord=111
@GetMapping("updateUserPassword")
public String updateUserPassword(int id,String passWord){
int rows= jdbcTemplate.update("UPDATE USER SET PASS_WORD = ? WHERE ID = ?",passWord,id);
return "執行成功,影響"+rows+"行";
}
//http://localhost:8888/deleteUserById?id=1
@GetMapping("deleteUserById")
public String deleteUserById(int id){
int rows= jdbcTemplate.update("DELETE FROM USER WHERE ID = ?",id);
return "執行成功,影響"+rows+"行";
}
//http://localhost:8888/batchSaveUserSql
@GetMapping("batchSaveUserSql")
public String batchSaveUserSql(){
String sql =
"INSERT INTO USER (USER_NAME,PASS_WORD) VALUES (?,?)" ;
List<Object[]> paramList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
String[] arr = new String[2];
arr[0] = "zhangsan"+i;
arr[1] = "password"+i;
paramList.add(arr);
}
jdbcTemplate.batchUpdate(sql,paramList);
return "執行成功";
}
//http://localhost:8888/getUserByUserName?userName=zhangsan0
@GetMapping("getUserByUserName")
public List getUserByUserName(String userName){
String sql = "SELECT * FROM USER WHERE USER_NAME = ?";
//寫法不少種
//下面列舉兩種寫法,均可以實現
//List<User> list= jdbcTemplate.query(sql,new Object[]{userName}, new BeanPropertyRowMapper(User.class));
List<User> list= jdbcTemplate.query(sql,new User(),new Object[]{userName});
return list;
}
//http://localhost:8888/getMapById?id=1
@GetMapping("getMapById")
public Map getMapById(Integer id){
String sql = "SELECT * FROM USER WHERE ID = ?";
Map map= jdbcTemplate.queryForMap(sql,id);
return map;
}
//http://localhost:8888/getUserById?id=1
@GetMapping("getUserById")
public User getUserById(Integer id){
String sql = "SELECT * FROM USER WHERE ID = ?";
User user= jdbcTemplate.queryForObject(sql,new User(),new Object[]{id});
return user;
}
}
複製代碼
使用execute方法建立User表數據庫
使用update方法,傳入參數sql語句,直接執行插入操做apache
使用update方法,傳入sql語句和對應字段值,進行插入操做api
使用update方法,傳入sql語句和對應字段值,進行修改操做
使用update方法,傳入sql語句和對應字段值,進行刪除操做
使用batchUpdate方法,傳入sql和參數集合,進行批量更新
使用query方法,傳入sql,實體對象,查詢參數,這裏就用到了實體類重寫的mapRow方法
使用queryForMap方法,傳入sql和參數,返回Map
使用queryForObject方法,傳入sql,實體對象,查詢參數,返回User實體類,這裏也用到了實體類重寫的mapRow方法
具體使用方法還有不少,請參考文檔:
docs.spring.io/spring/docs…
出現下圖錯誤不要擔憂,如圖
出現這個錯誤是由於sql在參數問號的時候多寫了引號形成的,這也是我在寫demo的時候犯下的錯誤。
源碼下載 :大老楊碼雲
我的網站:www.dalaoyang.cn