我们将学习如何在 Spring Boot 中使用 JDBC 进行数据访问。
Spring Boot 将日常企业应用研发中的各种场景都抽取出来,做成一个个的场景启动器(Starter),场景启动器中整合了该场景下各种可能用到的依赖,让用户摆脱了处理各种依赖和配置的困扰。
想要在 Spring Boot 中使用 JDBC 进行数据访问,第一步就是要在 pom.xml 中导入 JDBC 场景启动器:spring-boot-starter-data-jdbc,代码如下:
org.springframework.boot
spring-boot-starter-data-jdbc
查看 spring-boot-starter-data-jdbc 的依赖树,可以看到,该场景启动器默认引入了一个数据源:HikariCP,如下图所示:
JDBC 的场景启动器中并没有导入数据库驱动,我们需要根据自身的需求引入所需的数据库驱动。例如,访问 MySQL 数据库时,需要导入 MySQL 的数据库驱动:mysql-connector-java,示例代码如下:
mysql
mysql-connector-java
runtime
注意:Spring Boot 默认为数据库驱动程序做了版本仲裁,所以我们在导入数据库驱动时,可以不再声明版本。需要注意的是,数据库驱动的版本必须与数据库的版本相对应。
org.springframework.boot
spring-boot-starter-web
在application.xml配置文件中配置数据源:
#数据源连接信息
spring:
datasource:
username: root
password: 12345
url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
关于Web场景启动器可以参考我的另一篇博客:
Spring Boot spring-boot-starter-web(九)_人……杰的博客-CSDN博客
MainApplication.java:
package com.xj.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("com.xj")
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
User.java:
package com.xj.entity;
public class User {
private Long id;
//姓名
private String name;
//性别
private String gender;
//年龄
private Integer age;
//无参构造方法
public User(){}
//无参构造方法
public User(Integer age){
this.age = age;
}
//有参构造方法
public User(String name, String gender, Integer age){
this.name = name;
this.gender = gender;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User[ID:" + id + ", name:"+ name+", gender:" + gender + ", age:" + age + "]";
}
}
JdbcController.java:
package com.xj.controller;
import com.xj.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ResponseBody
@Controller
@RequestMapping("/jdbc")
public class JdbcController {
private final JdbcTemplate template;
public JdbcController(JdbcTemplate template) {
this.template = template;
}
@GetMapping
public List queryAllUser(){
//查询所有用户
String sql = "select * from user_table";
return template.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(User.class));
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id){
//根据主键查询一个用户
String sql = "select * from user_table where ID = ?";
return template.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
}
@PostMapping
public int addUser(@RequestBody User user){
//添加用户
String sql = "insert into user_table(name, gender, age) value(?, ?, ?)";
return template.update(sql, user.getName(), user.getGender(), user.getAge());
}
@PutMapping("/{name}")
public int editUserByName(@PathVariable String name,@RequestBody User user){
//根据姓名修改用户
String sql = "update user_table set age = ? where name = ?";
return template.update(sql, user.getAge(), name);
}
@DeleteMapping("/{id}")
public int deleteUserById(@PathVariable Long id){
//根据ID删除用户
String sql = "delete from user_table where id = ?";
return template.update(sql, id);
}
}
JdbcTest.java:
package com.xj.main;
import com.xj.entity.User;
import org.junit.jupiter.api.Test;
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.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
@SpringBootTest(classes = MainApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class JdbcTest {
private static final Logger log = LoggerFactory.getLogger(JdbcTest.class);
//数据源组件
@Autowired
DataSource dataSource;
//用于访问数据库的组件
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
private int port;
//连接测试
@Test
void contextLoads() throws SQLException {
System.out.println("默认数据源为:" + dataSource.getClass());
System.out.println("数据库连接实例:" + dataSource.getConnection());
//访问数据库
Integer i = jdbcTemplate.queryForObject("SELECT count(*) from `user_table`", Integer.class);
System.out.println("user 表中共有" + i + "条数据。");
}
@Test
void testJdbc() throws SQLException{
//查询所有用户
// TODO 如果是返回的集合,要用 exchange 而不是 getForEntity ,后者需要自己强转类型
ResponseEntity> response2 = restTemplate.exchange("http://localhost:" + port + "/jdbc", HttpMethod.GET, null, new ParameterizedTypeReference>() {
});
final List body = response2.getBody();
log.info("[查询所有] - [{}]\n", body);
//根据主键查询一个用户
Long userId = body.get(0).getId();
ResponseEntity response3 = restTemplate.getForEntity("http://localhost:" + port + "/jdbc/{id}", User.class, userId);
log.info("[主键查询] - [{}]\n", response3.getBody());
//添加一个用户
restTemplate.postForEntity("http://localhost:" + port + "/jdbc", new User("浮生若梦", "female", 23), Integer.class);
log.info("[添加用户成功]\n");
//根据姓名修改用户
String name = body.get(0).getName();
restTemplate.put("http://localhost:" + port + "/jdbc/{name}", new User(18), name);
log.info("[修改用户成功]\n");
//根据id删除用户
restTemplate.delete("http://localhost:" + port + "/jdbc/{id}", userId);
log.info("[删除用户成功]");
}
}
application.yml:
#默认配置
server:
port: 8080
#数据源连接信息
spring:
datasource:
username: root
password: 12345
url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
pom.xml:
4.0.0
com.xj.study
spring-boot-study-project
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.4.5
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-jdbc
org.springframework.boot
spring-boot-configuration-processor
true
org.webjars
jquery
3.6.0
org.springframework.boot
spring-boot-starter-thymeleaf
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-maven-plugin
repackage
数据库user_table表:
CREATE TABLE `user_table` (
`ID` bigint(10) NOT NULL AUTO_INCREMENT,
`NAME` varchar(50) DEFAULT NULL COMMENT '姓名',
`GENDER` varchar(10) DEFAULT NULL COMMENT '性别',
`AGE` int(11) DEFAULT NULL COMMENT '年龄',
`LAST_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`CREATE_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;
数据库user_table表:
1.Spring Boot JDBC访问数据库
2.一起来学SpringBoot | 第五篇:使用JdbcTemplate访问数据库 | 鏖战八方