Spring Data JPA : 查-分页排序

发布时间 2023-10-23 15:47:08作者: dreamstar

1.分页查询 

pageNumber是从0开始, pageNumber=0,pageSize=3 就是获取前3条 参考创建分页Pageable变量

创建Pageable对象,再查询

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class FruitServiceImpl implements FruitService {

    @Autowired
    private FruitRepository fruitRepository;

    // 分页获取
    @Override
    public List<Fruit> findAllPageable(Integer pageNumber, Integer pageSize) {

        Pageable pageable = PageRequest.of(pageNumber, pageSize); // 创建分页对象

        Page<Fruit> fruits = fruitRepository.findAll(pageable);
        Long total = fruits.getTotalElements(); // 符合条件的总记录条数
        List<Fruit> fruitList = fruits.getContent();// 这一页的所有记录
        return fruitList;
    }
}

2.先排序 再分页 查询 : 创建Sort对象,再用Sort对象创建 Pageable对象,再查询 参考Spring Data JPA 多属性排序

  •  根据一个字段排序   
  •  根据多个字段排序,排序方式一样 
  •  根据多个字段排序,排序方式不一样
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

@Service
public class FruitServiceImpl implements FruitService {

    @Autowired
    private FruitRepository fruitRepository;

    @Override
    public List<Fruit> findAllPageableBySort(Integer pageNumber, Integer pageSize) {

        Sort sort = Sort.by(Direction.DESC, "name");// 排序方式  根据name降序排列
        Pageable pageable = PageRequest.of(pageNumber, pageSize, sort);// 分页对象
    
        Page<Fruit> fruits = fruitRepository.findAll(pageable);// 查询

        Long total = fruits.getTotalElements(); // 符合条件的总记录条数
        List<Fruit> fruitList = fruits.getContent();// 这一页的所有记录

        return fruitList;
    }

    // 根据多个条件先排序 再分页获取
    @Override
    public List<Fruit> findAllPageableByMultiSort(Integer pageNumber, Integer pageSize) {

        // 根据多个条件排序 先根据name降序排列,再根据color的升序排列
        List<Order> orders = new ArrayList<Sort.Order>();
        orders.add(new Order(Direction.DESC, "name"));
        orders.add(new Order(Direction.ASC, "color"));
        Sort sort = Sort.by(orders);
        Pageable pageable = PageRequest.of(pageNumber, pageSize, sort);// 分页对象

        Page<Fruit> fruits = fruitRepository.findAll(pageable);// 查询
        
        Long total = fruits.getTotalElements(); // 符合条件的总记录条数
        List<Fruit> fruitList = fruits.getContent();// 这一页的所有记录

        return fruitList;
    }
}