Spring Boot JdbcTemplate 数据库操作入门
前言
本内容旨在展示如何在 Spring Boot 框架中利用 JdbcTemplate 组件进行数据库操作,并提供相应的示例代码供参考。
尽管数据库访问方式多样,此处重点讲解基于 Spring Boot 与 JdbcTemplate 结合的技术方案。
项目初始化
创建一个新的 Spring Boot 项目,并在 pom.xml 中添加 JDBC 相关依赖,完整的依赖配置如下所示:
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
com.dalaoyang
springboot_jdbc
0.0.1-SNAPSHOT
jar
springboot_jdbc
springboot_jdbc
org.springframework.boot
spring-boot-starter-parent
1.5.9.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-devtools
runtime
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-maven-plugin
项目的配置文件配置如下:
##端口号
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 的实体类,关键在于该类需实现 RowMapper 接口并重写 mapRow 方法,完整代码见下:
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 2026/7/25
*/
public class User implements RowMapper {
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;
}
}
常见的 CRUD 操作主要依赖以下三个核心方法:
1. execute 方法:用于直接执行原生 SQL 语句。 2. update 方法:适用于新增、修改和删除数据的操作。 3. query 方法:专门用于执行查询操作。
如同常规做法,此处通过 Controller 层注入 JdbcTemplate 来进行功能测试,完整代码如下,后续将对各个测试方法进行详细解析:
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 2026/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 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 list= jdbcTemplate.query(sql,new Object[]{userName}, new BeanPropertyRowMapper(User.class));
List 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;
}
}
测试方法解析
1. createTable 方法 调用 execute 方法来创建 User 数据表。
2. saveUserSql 方法 采用 update 方法,传入包含占位符的 SQL 字符串,直接执行插入动作。
3. saveUser 方法 使用 update 方法,同时传入 SQL 语句及对应的字段参数值,完成数据插入。
4. updateUserPassword 方法 运用 update 方法,传入 SQL 语句及更新所需的字段值,执行修改操作。
5. deleteUserById 方法 通过 update 方法,传入 SQL 语句及指定 ID 的参数值,执行删除逻辑。
6. batchSaveUserSql 方法 使用 batchUpdate 方法,传入 SQL 语句和参数集合,实现批量数据更新。
7. getUserByUserName 方法 调用 query 方法,传入 SQL、实体对象实例及查询参数,此过程利用了实体类中重写的 mapRow 方法。
8. getMapById 方法 使用 queryForMap 方法,传入 SQL 和参数,返回结果以 Map 形式呈现。
9. getUserById 方法 采用 queryForObject 方法,传入 SQL、实体对象及查询参数,返回 User 实体类实例,同样依赖于重写的 mapRow 方法。
更多具体用法请参阅官方文档:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html
注意事项
若遇到如图所示的错误提示,无需惊慌,情况如下:

该错误通常是因为在 SQL 参数的问号处错误地添加了引号所致,这也是编写 Demo 时容易出现的典型失误。
源码下载地址:大老杨码云
以上就是本文的全部内容,希望能为您的学习提供帮助,也欢迎继续支持本站。