Spring Data JPA简单查询接口方法速查

下表针对于简单查询,即JpaRepository接口(继承了CrudRepository接口、PagingAndSortingRepository接口)中的可访问方法进行整理。(1)先按照功能进行分类整理,分为保存、删除、查找单个、查找多个、其他5类。(2)再将不建议使用的方法置灰,此类方法多为CrudRepository接口、PagingAndSortingRepository接口中定义,后来JpaRepository接口中又定义了替代方法,更方便使用,比如:查找多个对象时,返回 List 比返回 Iterable 更容易处理。

二、五个接口详解
1、CrudRepository接口。
其中T是要操作的实体类,ID是实体类主键的类型。该接口提供了11个常用操作方法。
@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);//根据id 查询一个对象。返回对象本身,当对象不存在时,返回null
Iterable<T> findAll();//查询所有的对象
Iterable<T> findAll(Iterable<ID> ids);//根据id列表 查询所有的对象
boolean exists(ID id);//根据id 判断对象是否存在
long count();//计算对象的总个数
void delete(ID id);//根据id 删除
void delete(T entity);//删除一个对象
void delete(Iterable<? extends T> entities);//批量删除,集合对象(后台执行时,一条一条删除)
void deleteAll();//删除所有 (后台执行时,一条一条删除)
}
2、PagingAndSortingRepository接口。
该接口继承了CrudRepository接口,提供了两个方法,实现了分页和排序的功能了。
@NoRepositoryBean
public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort);// 仅排序
Page<T> findAll(Pageable pageable);// 分页和排序
}
3、JpaRepository接口。
该接口继承了PagingAndSortingRepository接口。
同时也继承QueryByExampleExecutor接口,这是个用“实例”进行查询的接口,后续再写文章详细说明。
@NoRepositoryBean
public interface JpaRepository<T, ID extends Serializable>
extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
List<T> findAll(); //查询所有对象,返回List
List<T> findAll(Sort sort); //查询所有对象,并排序,返回List
List<T> findAll(Iterable<ID> ids); //根据id列表 查询所有的对象,返回List
void flush(); //强制缓存与数据库同步
<S extends T> List<S> save(Iterable<S> entities); //批量保存,并返回对象List
<S extends T> S saveAndFlush(S entity); //保存并强制同步数据库
void deleteInBatch(Iterable<T> entities); //批量删除 集合对象(后台执行时,生成一条语句执行,用多个or条件)
void deleteAllInBatch();//删除所有 (执行一条语句,如:delete from user)
T getOne(ID id); //根据id 查询一个对象,返回对象的引用(区别于findOne)。当对象不存时,返回引用不是null,但各个属性值是null
@Override
<S extends T> List<S> findAll(Example<S> example); //根据实例查询