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<java.lang.String>)' 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);
  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值