SpringBoot 整合 JDBC
1、Spring Data简介
-
对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理。
-
Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中与 Spring Boot、Spring Cloud 等齐名的知名项目。
-
Sping Data 官网:https://spring.io/projects/spring-data
-
数据库相关的启动器 :可以参考官方文档:
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter
2、整合JDBC
-
创建项目,创建时引入相应模块
- Web
- Spring Web
- SQL
- JDBC API
- MySQL Driver
- Web
-
编写 yaml 配置文件,连接数据库
spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver
-
测试
@Autowired DataSource dataSource; @Test void contextLoads() throws SQLException { // 查看一下默认的数据源:class com.zaxxer.hikari.HikariDataSource System.out.println(dataSource.getClass()); // 获得数据库连接 Connection connection = dataSource.getConnection(); System.out.println(connection); // 关闭 connection.close(); }
3、JDBCTemplate
-
即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即JdbcTemplate。
-
数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。
-
Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用
测试:
-
编写一个Controller
package com.cheng.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; @RestController public class JDBCController { @Autowired JdbcTemplate jdbcTemplate; // 获取全部的用户 @RequestMapping("/userList") public List<Map<String, Object>> userList() { String sql = "select * from user"; List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); return maps; } // 增加一个用户 @RequestMapping("/addUser") public String addUser() { String sql = "insert into user(id, name, pwd) values(8, '小张', '111111')"; jdbcTemplate.update(sql); return "add OK"; } // 修改用户 @RequestMapping("/updateUser/{id}") public String updateUser(@PathVariable("id") int id) { String sql = "update user set name=?, pwd=? where id=" + id; //修改的数据 Object[] objects = new Object[2]; objects[0] = "张小小"; objects[1] = "000000"; jdbcTemplate.update(sql, objects); return "update OK"; } // 删除用户 @RequestMapping("/deleteUser/{id}") public String deleteUser(@PathVariable("id") int id) { String sql = "delete from user where id = ?"; jdbcTemplate.update(sql, id); return "delete OK"; } }
-
运行项目,然后测试
- http://localhost:8080/userList 获取全部用户
- http://localhost:8080/addUser 增加一个用户(固定测试数据)
- http://localhost:8080/updateUser/8 修改id为8的用户名和密码
- http://localhost:8080/deleteUser/8 删除id为8的用户