Spring Data是Spring的一个子项目,用于简化数据库的访问。Spring Data项目提供了访问操作数据的统一规范,该规范约定了对于关系型数据库和非关系型数据库操作的统一标准。
Spring Data通过提供Repository接口来约束数据访问的统一标准。其源码如下所示:
package org.springframework.data.repository; public interface Repository<T, ID> { }
该接口接收两个参数:
- 泛型T:表示当前所操作的实体类型
- ID:表示当前所操作的实体类型的主键类型
在Repository接口中不提供任何方法,操作数据时一般都是使用其子接口。在项目开发中,开发者只需定义自己项目的数据访问接口,然后让其继承Spring Data提供的这些子接口,就可以实现对数据的CRUD操作了。Repository接口包下常用的子接口有如下:
- CrudRepository:
- PagingAndSortingRepository:
CrudRepository
CrudRepository接口提供了最基本的对实体类的增删改查操作,其源码如下所示:
package org.springframework.data.repository; 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(); }
PagingAndSortingRepository
PagingAndSortingRepository接口继承自CrudRepository接口,除了拥有CrudRepository接口的功能之外,该接口还提供了分页和排序功能,其源码如下所示:
package org.springframework.data.repository; public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> { Iterable<T> findAll(Sort sort); Page<T> findAll(Pageable pageable); }
Spring Data JPA
Spring Data JPA是Spring Data技术下的子项目,使用Spring Data JPA访问数据只需要让数据访问接口继承JpaRepository接口即可。
JpaRepository
JpaRepository接口继承了PagingAndSortingRepository接口,其额外提供了更多的功能,源码如下所示:
package org.springframework.data.jpa.repository; public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> { List<T> findAll(); List<T> findAll(Sort sort); List<T> findAllById(Iterable<ID> ids); <S extends T> List<S> saveAll(Iterable<S> entities); void flush(); <S extends T> S saveAndFlush(S entity); void deleteInBatch(Iterable<T> entities); void deleteAllInBatch(); T getOne(ID id); @Override <S extends T> List<S> findAll(Example<S> example); @Override <S extends T> List<S> findAll(Example<S> example, Sort sort); }