Spring Boot 2.x实战69 - Spring Data 13 - Spring Data对Web MVC的支持

2.11 Web支持

Spring Data也给Web开发做了一定的支持,他通过@EnableSpringDataWebSupport开启支持。它主要导入了SpringDataWebConfiguration配置,通过它注册了DomainClassConverterPageableHandlerMethodArgumentResolver。由于SpringDataWebAutoConfiguration自动配置,我们无需再手工定义。

通过DomainClassConverter让我们可以通过控制器方法路径变量或者请求参数中直接查询Repository中的实例。

@RestController
@RequestMapping("/people")
public class PersonController {

    @GetMapping("/{id}")
    public Person findOne(@PathVariable("id") Person person){
        return person;
    }

}

在这里插入图片描述
通过PageableHandlerMethodArgumentResolver,控制器方法可以通过Pageable获得客户端传递的分页和排序参数,参数分别为:

  • page:页数,默认为0;
  • size:每页数量,默认为20;
  • Sort:排序
@RestController
@RequestMapping("/people")
public class PersonController {

    private PersonRepository personRepository;

    public PersonController(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    @GetMapping
    public Page<Person> findAllByPage(Pageable pageable){
       return personRepository.findAll(pageable);
    }

}

访问http://localhost:8080/people?page=0&size=2&sort=name,desc,通过参数即可达到分页和排序的功能。
在这里插入图片描述

新书推荐:

我的新书《从企业级开发到云原生微服务:Spring Boot 实战》已出版,内容涵盖了丰富Spring Boot开发的相关知识
购买地址:https://item.jd.com/12760084.html
在这里插入图片描述
主要包含目录有:

第一章 初识Spring Boot(快速领略Spring Boot的美丽)
第二章 开发必备工具(对常用开发工具进行介绍:包含IntelliJ IDEA、Gradle、Lombok、Docker等)
第三章 函数式编程
第四章 Spring 5.x基础(以Spring 5.2.x为基础)
第五章 深入Spring Boot(以Spring Boot 2.2.x为基础)
第六章 Spring Web MVC
第七章 数据访问(包含Spring Data JPA、Spring Data Elasticsearch和数据缓存)
第八章 安全控制(包含Spring Security和OAuth2)
第九章 响应式编程(包含Project Reactor、Spring WebFlux、Reactive NoSQL、R2DBC、Reactive Spring Security)
第十章 事件驱动(包含JMS、RabbitMQ、Kafka、Websocket、RSocket)
第11章 系统集成和批处理(包含Spring Integration和Spring Batch)
第12章 Spring Cloud与微服务
第13章 Kubernetes与微服务(包含Kubernetes、Helm、Jenkins、Istio)
多谢大家支持。

猜你喜欢

转载自blog.csdn.net/wiselyman/article/details/106611635
今日推荐