Spring Boot 整合 SpringData JPA與分頁
在Spring Boot中使用JPA,需要引入如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
1、JpaRepository
拿項目中一個dao層舉例:
public interface ProductCategoryRepository extends JpaRepository<ProductCategory,Integer> {
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}
所有dao層都會繼承***JpaRepository<實體類,主鍵類型>
***接口。
JpaRepository
接口的繼承關係圖:
其中重要的就是CrudRepository
和PagingAndSortingRepository
接口
1)CrudRepository接口
它定義了一些CRUD方法,所以繼承它的類可以直接獲得這些對數據庫操作的CRUD方法。
public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S var1);
<S extends T> Iterable<S> saveAll(Iterable<S> var1);
Optional<T> findById(ID var1);
boolean existsById(ID var1);
Iterable<T> findAll();
Iterable<T> findAllById(Iterable<ID> var1);
long count();
void deleteById(ID var1);
void delete(T var1);
void deleteAll(Iterable<? extends T> var1);
void deleteAll();
}
2)PagingAndSortingRepository接口
這是用來實現分頁接口
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort var1);
Page<T> findAll(Pageable var1);
}
分頁操作:
a)Controller層:
@GetMapping("/list")
public ModelAndView list(@RequestParam(value = "page" ,defaultValue="1") Integer page,
@RequestParam(value = "size",defaultValue = "10") Integer size,
Map<String,Object> map){
PageRequest request=new PageRequest(page-1,size);
Page<ProductInfo> productInfoPage=productService.findAll(request);
map.put("productInfoPage",productInfoPage);
map.put("currentPage",page);
map.put("size",size);
return new ModelAndView("product/list",map);
}
b)Service層:
@Override
public Page<ProductInfo> findAll(Pageable pageable) {
return repository.findAll(pageable);
}
c)Dao層:
public interface ProductInfoRepository extends JpaRepository<ProductInfo,String>{
}