【JPA】使用JPA實現分頁和模糊查詢


1、首先創建DAO層接口,實現JpaRepositoryJpaSpecificationExecutor兩個接口

  • JpaRepository<Admin, Integer> 泛型參數分別是:要查詢的實體(Entity),實體的主鍵類型
  • JpaSpecificationExecutor<Admin> 泛型參數:要查的實體
@Repository
public interface AdminRepository extends JpaRepository<Admin, Integer>, JpaSpecificationExecutor<Admin> {

}

2、Service層進行查詢操作

分頁模糊查詢三步驟:

  • 創建查詢條件對象
  • 創建分頁對象
  • 進行查詢操作
 /**
     * 分頁查找Admin
     *
     * @param query    查詢條件
     * @param pagenum  頁碼
     * @param pageSize 每頁顯示的數據
     * @return
     */
    @Override
    public Page<Admin> queryList(String query, Integer pagenum, Integer pageSize) {

        //查詢條件存在這個對象中
        Specification<Admin> specification = new Specification<Admin>() {
            //重新Specification的toPredicate方法
            @Override
            public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //我要模糊查詢的字段是adminName
                Path adminName = root.get("adminName");
                //criteriaBuilder.like模糊查詢,第一個參數是上一行的返回值,第二個參數是like('%xxx%')中,xxx的值
                Predicate predicate = criteriaBuilder.like(adminName, "%" + query + "%");
                return predicate;
            }
        };

        //分頁條件存在這個對象中
        PageRequest pageRequest = PageRequest.of(pagenum - 1, pageSize);

        //進行查詢操作,第一個參數是查詢條件對象,第二個參數是分頁對象
        Page<Admin> page = adminRepository.findAll(specification, pageRequest);

        //返回的數據都封裝在了Page<Admin>對象中
    
        return page;

    }

如果要獲得Page對象中的數據,可以直接使用page.getContent();方法

List<Admin> adminList = page.getContent();

Page對象中封裝的數據

{
    "data": {
        "content": [        //查出來的數據
            {
                "adminId": 3,
                "adminName": "b",
                "adminPassword": "b",
                "createTime": "2020-02-25T14:24:07.000+0000",
                "isBoss": "0"
            }
        ],
        "pageable": {
            "sort": {
                "sorted": false,
                "unsorted": true,
                "empty": true
            },
            "offset": 0,
            "pageNumber": 0,        //頁號,數據庫中的第一頁是從下標為0開始的
            "pageSize": 2,        //每頁顯示的條數
            "paged": true,
            "unpaged": false
        },
        "totalElements": 1,        //總條數
        "last": true,
        "totalPages": 1,            //總頁數
        "number": 0,
        "size": 2,
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "numberOfElements": 1,
        "first": true,
        "empty": false
    },
    "code": "code",
    "message": "message",
    "token": "token"
}

參考博客:Spring Data JPA使用Specification動態構建多表查詢、復雜查詢及排序示例


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM