1. 整合JDBC
1. SpringData
(1)介绍:对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理
2. 整合JDBC
(1)建立项目:导入JDBC-API和MySQL-Driver
(2)编写yml配置文件连接数据库
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
(3)测试
@SpringBootTest
class Springboot07DataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认的数据源
System.out.println(dataSource.getClass());
//class com.zaxxer.hikari.HikariDataSource
//查看链接
System.out.println(dataSource.getConnection());
//HikariProxyConnection@394190359 wrapping com.mysql.cj.jdbc.ConnectionImpl@17176b18
}
}
3. JDBCTemplate
(1)JDBCTemplate:有了数据源(HikariDataSource)就可以拿到数据库连接(Connection),就可以使用原生的JDBC语句进行操作数据库。
(2)即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC做了轻量级的封装,即JDBCTemplate,数据库所有CRUD方法都在JDBCTemplate类中
(3)SpringBoot不仅提供了数据源,同时默认配置好了JDBCTemplate放在容器中,只需要注入使用即可
(4)测试:编写一个Controller,注入JDBCTemplate,编写方法进行测试
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/all")
//http://localhost:8080/all
public List<Map<String,Object>> getAll(){
String sql = "select * from user";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
return list;
}
@GetMapping("/add")
//http://localhost:8080/add
public String addUser(){
String sql = "insert into user(name,age) values('赵六','26')";
int update = jdbcTemplate.update(sql);
if (update>0) {
return "addUser OK";
}else{
return "false";
}
}
@GetMapping("/update/{id}")
//http://localhost:8080/update/1
public String updateUser(@PathVariable("id")int id){
String sql = "update user set name = ?,age = ? where id = " + id;
Object[] objects = new Object[2];
objects[0] = "小张三";
objects[1] = 13;
int update = jdbcTemplate.update(sql, objects);
if (update>0) {
return "updateUser OK";
}else{
return "false";
}
}