不多说,先代码,后解释
问题代码:
Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
Pageable pageable = PageRequest.of(0,size,sort);
报错代码:
Error:(73, 29) java: PageRequest(int,int,org.springframework.data.domain.Sort) 在 org.springframework.data.domain.PageRequest 中是 protected 访问控制
问题分析:
很明显,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
解决方案:
按照新版本源码提供的方案修改即可:
Sort sort = Sort.by(Sort.Order.desc("create_date"));
Pageable pageable =PageRequest.of(Integer.parseInt(page), Integer.parseInt(size), sort);