JPA基础查询方法
1、整体认识
Spring Data是一个基于Spring 的数据访问编程模型。Spring Data Common是Spring Data所有模块的公共部分。
Spring Data的主要子项目有:Spring Data Common、Spring Data Gemfire、Spring Data JPA、Spring Data KeyValue等10个。社区支持子项目有8个,其他子项目3个。
2、Spring Data JPA主要类及结构图
Spring Data JPA的7个接口:Repository、CrudRepository、PagingAndSortingRepository、QueryByExampleExecutor、JpaRepository、JpaSpecificationExecutor、QueryDslPredicateExecutor。
Spring Data JPA两个实现类:SimpleJpaRepository、QueryDslJpaRepository。
JPA底层封装类:EntityManager、EntityManagerImpl。
结构图如下:
3、JPA的基础查询方法
1)Repository为Spring Data中最底层的接口、最顶级的父类。这个接口定义了所有Repository操作的实体和ID两个泛型参数。
源码如下:
public interface Repository<T, ID extends Serializable>{
}
只要继承该接口,就能使用Spring JPA的很多约定方法查询和注解查询。
2)CrudRepository
package org.springframework.data.repository;
import java.io.Serializable;
@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
<S extends T> S save(S entity);
<S extends T> Iterable<S> save(Iterable<S> entities);
T findOne(ID id);
boolean exists(ID id);
Iterable<T> findAll();
Iterable<T> findAll(Iterable<ID> ids);
long count();
void delete(ID id);
void delete(T entity);
void delete(Iterable<? extends T> entities);
void deleteAll();
}
保存/更新实体:SimpleJpaRepository的实现方法,先判断是否存在,再判断是新增还是更新。
删除实体:SimpleJpaRepository的实现方法,先查询是否存在,再进行删除。
3)PagingAndSortingRepository
继承了CrudRepository的所有基本方法,增加了分页、排序等对结果进行限制的、基本的、常用的分页方法。
使用示例:
//排序并分页
@GetMapping(path = "/page")
@ResponseBody
public Page<User> getAllUserByPage(){
return userPagingAndSortingRepository.findAll(new PageRequest(1, 20, new Sort(new Sort.Order(Sort.Direction.ASC, "name"))));
}
//排序查询
@GetMapping(path = "/sort")
@ResponseBody
public Page<User> getAllUserWithSort(){
return userPagingAndSortingRepository.findAll(new Sort(new Sort(new Sort.Order(Sort.Direction.ASC, "name"))));
}
以上三个类是为兼容NoSQL进行的一些抽象封装,JpaRepository是对关系型数据库进行封装。
4)JpaRepository
它与CrudRepository比较,增加支持了QueryByExample,批量删除,默认将查询结果变为List。