技術(shù)框架
- Spring Boot
- Spring JPA
- Maven
Maven 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Controller
@RequestMapping("/list")
public String list(int parentid, int page, int size){
return categoryService.getList(parentid, page, size);
}
Service
public String getList(int parentid, int page, int size){
StringBuilder sb = new StringBuilder();
Sort sort = new Sort(Direction.DESC, "cid");//指定排序字段
Page<Category> pp = categoryRepository.findByParentid(parentid, new PageRequest(page, size, sort));
List<Category list = pp.getContent();
for(Category item : list) {
//logic process
}
return sb.toString();
}
Reponsitory (重點(diǎn))
最簡潔的寫法
public interface CategoryRepository extends JpaRepository<Category, Integer> {
Page<Category> findByParentid(int parentid, Pageable pageable);
}
手動(dòng)寫SQL的寫法
public interface CategoryRepository extends JpaRepository<Category, Integer> {
@Query(value="select * from Category where parentid =?1 order by cid desc /* #pageable# */ ",countQuery="select count(*) from Category where parentid = ?1",nativeQuery = true)
Page<Category> findByParentid(int parentid, Pageable pageable);
}
總結(jié)
本文只貼出了主要部分代碼蝇庭,提供了實(shí)現(xiàn)的思路孕蝉。
作者使用的是H2的數(shù)據(jù)庫埠戳,很奇怪的一點(diǎn)就是在select語句后面需要添加一小段注釋/* #pageable# */
stackoverflow上有一篇文章對這點(diǎn)進(jìn)行了討論嘴纺,上面有人提到mysql的處理方案
mysql的代碼示例
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1 ORDER BY ?#{#pageable}",
countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
nativeQuery = true)
Page<User> findByLastname(String lastname, Pageable pageable);
}
使用JPA實(shí)現(xiàn)數(shù)據(jù)訪問冗荸,代碼非常簡潔,沒有那么多復(fù)雜的DAO代碼愈涩,非常優(yōu)雅。