Spring boot 分页方法过时解决

1.问题表现

源代码为:

Sort sort = new Sort(Sort.Direction.DESC, "login_time");
Pageable pageable = new PageRequest(Integer.parseInt(page), Integer.parseInt(size), sort);

报错代码为:

'Sort(org.springframework.data.domain.Sort.Direction,java.util.List)' has private access in 'org.springframework.data.domain.Sort'

PageRequest(int, int, org.springframework.data.domain.Sort)' has protected access in 'org.springframework.data.domain.PageRequest

2.问题分析

很明显,Spring Boot新版本中已经升级相关的类,不支持原来的写法了。

Sort为例,我们看一下他的源码:

public class Sort implements Streamable<Sort.Order>, Serializable {
    private static final long serialVersionUID = 5737186511678863905L;
    private static final Sort UNSORTED = by();
    public static final Sort.Direction DEFAULT_DIRECTION;
    private final List<Sort.Order> orders;

    private Sort(Sort.Direction direction, List<String> properties) {
        if (properties != null && !properties.isEmpty()) {
            this.orders = (List)properties.stream().map((it) -> {
                return new Sort.Order(direction, it);
            }).collect(Collectors.toList());
        } else {
            throw new IllegalArgumentException("You have to provide at least one property to sort by!");
        }
    }

    public static Sort by(String... properties) {
        Assert.notNull(properties, "Properties must not be null!");
        return properties.length == 0 ? unsorted() : new Sort(DEFAULT_DIRECTION, Arrays.asList(properties));
    }

    public static Sort by(List<Sort.Order> orders) {
        Assert.notNull(orders, "Orders must not be null!");
        return orders.isEmpty() ? unsorted() : new Sort(orders);
    }

    public static Sort by(Sort.Order... orders) {
        Assert.notNull(orders, "Orders must not be null!");
        return new Sort(Arrays.asList(orders));
    }

    public static Sort by(Sort.Direction direction, String... properties) {
        Assert.notNull(direction, "Direction must not be null!");
        Assert.notNull(properties, "Properties must not be null!");
        Assert.isTrue(properties.length > 0, "At least one property must be given!");
        return by((List)Arrays.stream(properties).map((it) -> {
            return new Sort.Order(direction, it);
        }).collect(Collectors.toList()));
    }

这里Sort的属性已有原来的public变为private了,而且我们原来的方法变更为Sort.by()

同理,PageRequest的原有的属性由public变为procted


3.解决方案

按照新版本源码提供的方案修改即可:

Sort sort = Sort.by(Sort.Order.desc("create_date"));
Pageable pageable =PageRequest.of(Integer.parseInt(page), Integer.parseInt(size), sort);

你可能感兴趣的:(spring,boot)