SpringData
官网:https://spring.io/projects/spring-data
数据库相关启动器(官方文档):
- 应用于数据访问层,无论是SQL(关系型数据库)还是NOSQL(非关系型数据库),StringBoot底层都是采用SpringData的方式进行统一处理
- Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷。
- 可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能
编写springdata程序
1、创建springboot项目(勾选mysql driver和jdbc)
2、在resources资源目录下创建配置文件application.yaml
- 由于springboot连接书库需要添加时区,随便找个加上即可
- 以及不知为何即使是mysql5.0版本的driver也要加上cj
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
Access denied for user '***'@'localhost' (using password: YES)
是因为阿里云创建的springboot的application里面已经有配置了,删除/注销就行
注意:
- 在springboot中有很多配置好的bean——xxxTemplate(模板),拿来即用
- jdbc Template,就像上面那个
- redis Template,
编写sql测试
1、需要在pom.xml导入web的启动器,@RestController注解才能生效
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、编写controller层代码
新建查询sql语句并利用jdbc模板去执行sql语句。
@RestController
public class JdbcController {
@Autowired//springboot集成好的,直接导入类,使用里面的方法即可
JdbcTemplate jdbcTemplate;
//查询数据库的所有信息
//没有实体类,数据库中的东西,如何获取。使用Map
@GetMapping("/userList")
public List<Map<String,Object>> userList(){
String sql = "select * from mybatis.user";//sql语句
List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
return list_maps;
}
}
3、然后启动应用程序
异常:程序包org.springframework.web.bind.annotation不存在
则需要idea配置一些,高版本才有这种情况
4、测试新增数据
//增加sql语句
@GetMapping("/addUser")
public String addUser(){
String sql = "insert into mybatis.user values (22,'赵六','88263')";
int update = jdbcTemplate.update(sql);
return "修改行数:"+update;
//而且这里没有写事务,但是却修改数据持久化到数据库了,说明springboot后台自动提交事务了
}
5、测试修改数据
这里既用到了预编译(还是restFull风格)
又用到了拼接字符串
值得深思
//修改sql语句
@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") int id){
String sql = "update mybatis.user set name=?,pwd=? where id = " + id;//拼接sql
//封装数据
Object[] objects = new Object[2];
objects[0] = "赵本山";
objects[1] = "31dsafg";
//执行的是一个预编译sql
int update = jdbcTemplate.update(sql,objects);
return "updateUser修改行数:"+update;
//而且这里没有写事务,但是却修改数据持久化到数据库了,说明springboot后台自动提交事务了
}
6、测试删除数据
//删除sql语句
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") int id){
String sql = "delete from mybatis.user where id = ?";
int update = jdbcTemplate.update(sql,id);//预编译参数
return "deleteUser修改行数:"+update;
//而且这里没有写事务,但是却修改数据持久化到数据库了,说明springboot后台自动提交事务了
}
导入jdbc包后,它将所有数据源导入进来了
看源码发现它支持五种数据源,默认是Hikari
上面五种数据源之一就有自定义数据源,只要通过配置即可
@ConditionalOnProperty(name = "spring.datasource.type")