翻译: Core concepts
Spring数据存储库抽象中的中心接口是repository
。它采用要管理的域类以及域类的ID类型作为类型参数。此接口主要充当标记接口,以捕获要使用的类型,并帮助您发现扩展此接口的接口。CrudRepository
为被管理的实体类提供了复杂的CRUD功能。
例3:**CrudRepository
** 接口
public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S entity); //保存指定的实体
Optional<T> findById(ID primaryKey); //返回给定id的实体
Iterable<T> findAll(); //返回所有实体
long count(); //统计实体个数
void delete(T entity); //删除给定的实体
boolean existsById(ID primaryKey); //判断给定id的实体是否存在
// … more functionality omitted.
}
我们还提供特定于持久性技术的抽象,例如
JpaRepository
或MongoRepository
。这些接口扩展了CrudRepository
,在CrudRepository
的通用接口外,还增加拓展了公开了其他基础持久性技术的接口功能。
在CrudRepository
之上,有一个PagingAndSortingRepository
抽象接口,它添加了其他方法来简化对实体的分页访问:
例4:**PagingAndSortingRepository
**接口
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}
获取页面大小为20的user
实体列表第二页的代码如下所示:
PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(PageRequest.of(1, 20));
注:Page从0开始
除了查询方法之外,还可以使用计数和删除查询的查询派生。以下列表显示派生计数查询的接口定义:
例5:计数查询派生
interface UserRepository extends CrudRepository<User, Long> {
long countByLastname(String lastname);
}
以下列表显示了派生的删除查询的接口定义:
例6:删除查询派生
interface UserRepository extends CrudRepository<User, Long> {
long deleteByLastname(String lastname);
List<User> removeByLastname(String lastname);
}
Dao
public interface ShipDao extends JpaRepository<ShipPO,Integer> {
Page<ShipPO> findByRegion(String region,Pageable pageable);
}
Service
@RequestMapping(value = "/ship",method = RequestMethod.GET)
public List<ShipPO> GetShip(
@RequestParam(value = "region",required = false,defaultValue = "none") String region
){
Pageable pageable = PageRequest.of(page,5, Sort.by(Sort.Direction.DESC,"sdate"));
//无区域限制
//根据地区查询,有地区限制 无状态限制
shiplist = shipDao.findByRegion(region,pageable).get().collect(Collectors.toList());
return shiplist;
}