💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] # Repository分析 创建的 Repository 只要继承 JpaRepository 即可,就会帮我们⾃动⽣成很多内置⽅法 ⽐如 findByUserName 会⾃动⽣产⼀个以 userName 为参数的查询 ⽅法,⽐如 findAll 会⾃动查询表⾥⾯的所有数据等 ![](https://img.kancloud.cn/bb/93/bb933c45537b49ce54c08f6d25bf579d_656x609.png) 发现 JpaRepository 继承 PagingAndSortingRepository 和 QueryByExampleExecutor, PagingAndSortingRepository 类主要负责排序和分⻚页内容, QueryByExampleExecutor 提供了很多示例的查 询⽅法,如下: ~~~ public interface QueryByExampleExecutor<T> { <S extends T> S findOne(Example<S> example); //根据“实例”查找⼀个对象 <S extends T> Iterable<S> findAll(Example<S> example); //根据“实例”查找⼀批对 象 <S extends T> Iterable<S> findAll(Example<S> example, Sort sort); //根据“实例” 查找⼀批对象,且排序 <S extends T> Page<S> findAll(Example<S> example, Pageable pageable); //根据“ 实例”查找⼀批对象,且排序和分⻚ <S extends T> long count(Example<S> example); //根据“实例”查找,返回符合条件的对象 个数 <S extends T> boolean exists(Example<S> example); //根据“实例”判断是否有符合条件的对象 } ~~~ 继承 JpaRepository 的会⾃动拥有上述这些⽅法和排序、分⻚页功能。查看源码我们发现 PagingAndSortingRepository ⼜继承了 CrudRepository。CrudRepository 的源码如下 ~~~ @NoRepositoryBean public interface CrudRepository<T, ID> extends Repository<T, ID> { <S extends T> S save(S entity); <S extends T> Iterable<S> saveAll(Iterable<S> entities); Optional<T> findById(ID id); boolean existsById(ID id); Iterable<T> findAll(); Iterable<T> findAllById(Iterable<ID> ids); long count(); void deleteById(ID id); void delete(T entity); void deleteAll(Iterable<? extends T> entities); void deleteAll(); } ~~~ 从 CrudRepository 的源码可以看出 CrudRepository 内置了我们最常⽤的增、删、改、查的⽅法,⽅便我们 去使⽤,因为 JpaRepository 继承了 PagingAndSortingRepository,PagingAndSortingRepository 继承了 CrudRepository,所以继承 JpaRepository 的类也默认拥有了上述⽅法