对于数据访问层,无论是SQL(关系型数据库)还是NOSQL(非关系型数据库),
Spring Boot 底层都是采用 Spring Data 的方式进行统一处理
创建一个新项目,依赖勾选 JDBC API、MySQL Driver
项目创建好后,pom.xml 文件显示依赖的 jar 包
<dependencies>
<!-- JDBC依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MySQL依赖 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
resources 目录下创建 application.yml 文件
serverTimezone=UTC,时区配置
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
连接 Mysql
测试类:getConnection() 连接数据库
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class JdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认数据源
System.out.println(dataSource.getClass());
//获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
//关闭
connection.close();
}
}
JdbcTemplateConfiguration.class 源码:
注册了 Bean,可以拿到 JdbcTemplate,只需要注入 DataSource 数据源和 Properties 配置
而这些都已经有了,所以直接拿来用即可
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnMissingBean({JdbcOperations.class})
class JdbcTemplateConfiguration {
JdbcTemplateConfiguration() {
}
@Bean
@Primary
JdbcTemplate jdbcTemplate(DataSource dataSource, JdbcProperties properties) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
JdbcProperties.Template template = properties.getTemplate();
jdbcTemplate.setFetchSize(template.getFetchSize());
jdbcTemplate.setMaxRows(template.getMaxRows());
if (template.getQueryTimeout() != null) {
jdbcTemplate.setQueryTimeout((int)template.getQueryTimeout().getSeconds());
}
return jdbcTemplate;
}
}
pom.xml 文件导入 web 依赖:
<!-- web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
JdbcController 类:实现 CRUD
@Autowired 对类成员变量、方法及构造函数进行标注,让 spring 完成 bean 自动装配的工作
package com.demo.controller;
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.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JdbcController {
@Autowired
JdbcTemplate jdbcTemplate;
//查询数据的所有信息
@GetMapping("/userList")
public List<Map<String, Object>> userList(){
String sql = "select * from user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
//添加
@GetMapping("/addUser")
public String addUser(){
String sql = "insert into mybatis.user(id,name,pwd) values (5,'张三5','123')";
jdbcTemplate.update(sql);
return "ok";
}
//修改
@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") int id){
//方法一
String sql = "update mybatis.user set name=?,pwd=? where id="+id;
//方法二 封装
Object[] objects = new Object[2];
objects[0] = "张三";
objects[1] = "123";
jdbcTemplate.update(sql,objects);
return "ok";
}
//删除
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") int id){
String sql = "delete from mybatis.user where id=?";
jdbcTemplate.update(sql,id);
return "ok";
}
}