@[]
3.1 Spring Boot数据访问概述
概述
Spring Boot默认采用整合SpringDatal的方式统一处理数据访问层通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。
- Spring Boot提供的常见数据库依赖启动器
名称 | 对应数据库 |
---|---|
spring-boot-starter-data-jpa | Spring Data JPA Hibernate |
spring-boot-starter-data-mongodb | MongoDB Spring Data MongoDB |
spring-boot-starter-data-neo4j | Neo4j图数据库 Spring Data Neo4j |
spring-boot-starter-data-redis | Redis |
3.2Spring Boot整合MyBatis
基础环境搭建
- 搭建步骤:
-
数据准备:创建数据库、数据表并插入一定的数据
- ①创建数据库
CREATE DATABASE springbootdata;
- ②创建数据表t_article
CREATE TABLE `t_article`( `id` int(20) NOT NULLAUTO INCREMENT COMMENT'文章id', `title`varchar(200) DEFAULT NULL COMMENT'文章标题', `content` longtext COMMENT'文章内容', PRIMARY KEY (`id`) )ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
- ③向数据表t_article插入相关数据
INSERT INTO `t_article` VALUES('1','Spring Boot基础入门','从入门到精通讲解...'); INSERT INTO `t_article` VALUES('2','Spring Cloud:基础入门','从入门到精通讲解...');
- ④创建数据表t_comment
CREATE TABLE `t_comment`( `id` int(20) NOT NULLAUTO_INCREMENT COMMENT'评论id', `content` longtext COMMENT '评论内容', `author` varchar(200)DEFAULT NULL COMMENT'评论作者', `aid` int(20)DEFAULT NULL COMMENT'关联的文章id', PRIMARY KEY (`id`) )ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
- ⑤向数据表t comment插入相关数据
INSERT INTO `t_comment` VALUES('1','很全、很详细','狂奔的蜗牛',1); INSERT INTO `t_comment` VALUES('2','赞一个','tom','1'); INSERT INTO `t_comment` VALUES('3','很详细','kitty','1'); INSERT INTO `t_comment` VALUES('4','很好,非常详细','张三','1'); INSERT INTO `t_comment` VALUES(‘5',很不错',’张杨',2');
-
创建项目,引入相应的启动器:使用Spring Initializr的方式构建项目,选择MySQL和MyBatis依赖,编写实体类。
-
⑥创建项目,引入MySQL和MyBatis的依赖启动器
-
⑦编写实体类Commenta和Article
Comment
public class Comment{ private Integer id; private String content; private String author; private Integer ald; get、set方法 }
Article
public class Article{ private Integer id; private String title; private String content; private List<Comment>commentList; get、set方法 )
-
-
编写配置文件:在配置文件中进行数据库连接配置以及进行第三方数据源的默认参数覆盖。
- ⑧编写配置文件
1、在全局配置文件中进行数据库连接配置
spring.datasource.url-jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123
2、设置数据源类型配置(以阿里巴巴的Druid数据源为例)
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency>
- ⑨在全局配置文件中设置属性
如果在开发过程中,需要对这些第三方Druid的运行参数进行重新设置必须在application.properties配置文件中进行默认参数覆盖。
#对数据源默认值进行了修改 数据源类型 spring.datasource.type = com.alibaba.druid.pool.DruidDataSource 初始化连接数 spring.datasource.initialSize=20 #最小空闲数 spring.datasource.minIdle=10 #最大连接数 spring.datasource.maxActive=100
- ⑧编写配置文件
-
使用注解方式整合MyBatis
- 整合步骤:
-
1.创建Mapper接口文件:@Mapper
-
2.编写测试方法进行接口方法测试及整合测试
因为字段名和实体类中的属性名不一致,字段名符合数据库的规则(使用_),实体类中的属性名符合Java的规则(使用驼峰)
-
使用配置文件方式整合MyBatis
- 整合步骤
-
1.创建Mapper接口文件:@Mapper
-
2.创建XML映射文件:编写对应的SQL语句
-
3.在全局文件中配置XML映射文件路径以及实体类别名映射路径
-
4.编写测试方法进行接口方法测试及整合测试
-
3.3Spring Boot整合PA
Spring Data JPA介绍
- Spring Data JPA基本使用
- 1.编写ORM实体类:实体类与数据表进行映射,并且配置好映射关系。
@Entity(name ='t comment") public class Discuss{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "a_id") private Integer ald; //省略getXX()和setXX()方法 }
- 2.编写Repository接口:针对不同的表数据操作编写各自对应的Repositor接口,并根据需要编写对应的数据操作方法。
nativeQuery=true支持原生sql语句,可以用*
- 使用Spring Data JPA进行数据操作的多种实现方式
- 如果自定义接口继承了JpaRepository接口,则默认包含了一些常用的CRUD方法。
- 自定义Repository接口中,可以使用@Query注解配合SQL语句进行数据的查、改、删操作
- 自定义Repository接口中,可以值接使用方法名关键字进行查询操作
- 自定义Repository接口中的@Transactional注解
- 在自定义的Repository接口中,针对数据的变更操作(修改、删除),无论是否使用了@Query注解,都必须在方法上方添加@Transactional注解进行事务管理,否则程序执行就会出现InvalidDataAccessApiUsageException异常。
- 如果在调用Repository接口方法的业务层Service类上已经添加了**@Transactional注解进行事务管理**,那么Repository接口文件中就可以省略@Transactional注解。
- 变更操作,要配合使用@Query与Modify注解
- 在自定义的Repository接口中,使用@Queryi注解方式执行数据变更操作(修改、删除),除了要使用@Queryi注解,还必须添加@Modifying注解表示数据变更。
- JPA还支持使用Example实例进行复杂条件查询
使用Spring Boot整合JPA
- 整合步骤
-
在pom文件中添加Spring Data JPA依赖启动器
①在pom文件中添加Spring Data JPA依赖启动器<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
-
编写ORM实体类
②编写ORM实体类@Entity(name="t_comment") public class Discuss{ @Id @GeneratedValue(strategy GenerationType.IDENTITY) private Integer id; private String content; private String author; @Column(name ="a_id") private Integer ald; }
-
编写Repository接口
③编写Repository接▣DiscussRepository
1.查询author非空的Discuss评论集合public List<Discuss>findByAuthorNotNull() ;
2、根据文章id分页查询Discuss评论集合
@Query("SELECT c FROM t_comment c WHERE c.ald = ?1") public List<Discuss>getDiscussPaged(Integer aid,Pageable pageable);
3、使用元素SQL语句,根据文章id分页查询Discuss评论集合
@Query(value ="SELECT FROM t_comment WHERE a_Id = ?1",nativeQuery = true) public List<Discuss>getDiscussPaged2(Integer aid,Pageable pageable);
4、根据评论id修改评论作者author
@Transactional @Modifying @Query("UPDATE t_comment c SET c.author =?1 WHERE c.id =?2") public int updateDiscuss(String author,Integer id);
5、根据评论id删除评论
@Transactional @Modifying @Query("DELETE FROM t_comment c WHERE c.id =?1") public int deleteDiscuss(Integer id);
-
编写单元测试进行接口方法测试及整合测试
④
编写测试方法@Run With(SpringRunner .class) @SpringBootTest public class JpaTests @Autowired private DiscussRepository repository; @Test public void selectCommentByKeysO{ List<Discuss>list = repository.findByAuthorNotNullO; System.out.println(list); }
-
3.4Spring Boot整合Redis
Redis介绍
- Redis简介
Redis是一个开源(BSD许可)的、内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,并提供多种语言的API。 - Redis优点
1.存取速度快:Redis速度非常快,每秒可执行大约110000次的设值操作,或者执行81000次的读取操作。
2.支持丰富的数据类型:Redis支持开发人员常用的大多数数据类型,例如列表、集合、排序集和散列等。
3.操作具有原子性:所有Rdis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新后的值。
4.提供多种功能:Redis提供了多种功能特性,可用作非关系型数据库、缓存中间件、消息中间件等。
使用Spring Boot整合Redis
-
整合步骤:
- 在pom文件中添加Spring Data Redis依赖启动器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
编写实体类
@RedisHash("persons") public class Person{ @Id private String id; @Indexed private String firstname; @Indexed private String lastname; private Address address; private List<Family>familyList; }
public class Address{ @Indexed private String city; @Indexed private String country; }
public class Family{ @Indexed private String type; @Indexed private String username;}
-
编写Repository接口
与Repository接口PersonRepositorypublic interface PersonRepository extends CrudRepository<Person,String>{ List<Person>findByLastname(String lastname); Page<Person>findPersonByLastname(String lastname,Pageable page); List<Person>findByFirstnameAndLastname(String firstname,String lastname); List<Person>findByAddress_City(String city); List<Person>findByFamilyList_Username(String username);
-
在全局配置文件application.properties中添加Redis数据库连接配置
④Redis数据库连接配置spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=
-
编写单元测试进行接口方法测试以及整合测试
编写测试方法整合测试@Run With(SpringRunner.class) @SpringBootTest public class RedisTests{ @Autowired private PersonRepository repository; @Test public void selectPerson(){ List<Person>:list=repository..findByAddress_City("北京"); System.out.println(list);} ... }