最近做的项目持久层是用的Spring Data,对于基本的数据访问提供了便利的方法,本文将针对Spring Data讲解它的使用,如有不足之处还请多多指教。
引言
什么是Spring Data?
Spring Data 是持久层通用解决方案,支持关系型数据库Oracle,MySQL,非关系型数据库NoSql,并支持云服务的开源框架,其主要目标是使得对数据的访问变得方便快捷。
正文
Spring Data简介
Spring Data应用场景: 减少数据访问层的开发量
Spring Data JPA,Spring Data Mongo DB,Spring Data Redis(C语言编写,支持网络支持内存,键值对数据库),Spring Data Solr
Spring Data配置
使用SpringData先配置好EntityManagerFactory

配置Spring data

Spring Data JPA
主要来看看Spring Data JPA提供的接口,也是Spring Data JPA的核心概念:
- Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别。
- CrudRepository :是Repository的子接口,提供CRUD的功能
- PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能
- JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等。
- JpaSpecificationExecutor:用来做负责查询的接口
- Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可
接口配置
编写实体类,添加注解@Entity标识是一个实体类,@Id标识是主键,@GeneratedValue标识自增,@Column(length = 20)设置生成表的类型长度
Repository接口详解
Repository接口是一个空接口,Spring Data的核心接口,不提供任何方法
public interface Repository<T,ID extends Serializable> {}
@RepositoryDefinition注解,(domainClass = Employ.class, idClass = Integer.class),添加注解能达到不用extends Repository的功能
Repository Query Specifications,Query Annotation,Update/Delete/Transaction Repository HierarchyCrudRepository : 继承Repository,实现增删改查操作
PagingAndSortingRespository,继承CrudRepository,实现了分页和排序
JpaRepository, 继承PagingAndSortingRepository,实现了JPA规范相关的方法,JpaSpecificationExecutor
Repository中查询方法定义规则和使用
Spring Data中查询方法名称的定义规则

Spring Data完成复杂查询方法名称的命名

对于按照方法命名规则来使用的话,有弊端
1)方法名会比较长,约定大于配置 2)对于一些复杂的查询,是很难实现
Query注解的使用
在Respository方法中使用,不需要遵循查询方法命名规则,只需要将@Query定义在Respository中的方法之上即可

?1和?2代表参数,或者使用@Param(“xx”)定义的参数
更新和删除操作整合事务的使用
@Modifying注解使用 @Modfying结合@Query注解执行更新操作

@Transactional在Service实现类中使用
Spring Data JPA 高级应用
CrudRepository接口使用详解

创建接口XXXCrudRepository继承CrudRepository,同时添加更新删除操作也要添加到事务Service中去

PagingAndSortingRespository接口使用详解
该接口包含分页和排序的功能
带排序的查询: findAll(Sort sort)
带排序的分页查询: findAll(Pageable pageable)
创建接口 XXXPagingAndSortingRepository 继承 PagingAndSortingRepository<XX,Integer>

只查询分页数据时

JPARepository接口使用详解
findAll,findAll(Sort,sort),save(entities),flush,deleteInBatch(entities)
测试查询和是否存在两个方法

JpaSpecificationExecutor接口使用详解
Specification封装了JPA Criteria查询条件
public interface EmployeeJpaSpecificationRepository extends JpaRepository<Employee,Integer>,JpaSpecificationExecutor<Employee> {}三个参数分别代表, root: 查询的类型, query: 添加查询条件, cb: 构建Predicate

其他用法
@Query(value = "select * from table where date > ?1 and name in ?2")List
MySQL查询大于当前日期,2019-06-01这种
SELECT * FROM tour_order t WHERE t.use_time < curdate() and t.`status` = 20; 本人使用有限,关于Spring Data的用法就这么多,对于其他Spring Data的知识使用到了再更新出来,欢迎有疑问和想法的朋友交流 ^_^