Spring Data JPA 对MVC的支持
@EnableSpringDataWebSupport
启用Spring Data的Web支持模块
@Configuration @EnableWebMvc @EnableSpringDataWebSupport public class WebConfig { }
Spring容器将会帮我们配置注册几个基本组成部分
- DomainClassConverter: 让Spring MVC解决的实例库管理域类来自请求参数或路径变量
- HandlerMethodArgumentResolver: 实现让Spring MVC解决可分页和排序实例来自请求参数
DomainClassConverter
允许使用域类型在Spring MVC控制器直接方法签名
@RestController @RequestMapping("/user") public class SystemUserController { @GetMapping("/{id}") public SystemUser getUserInfo(@PathVariable("id") SystemUser systemUser){ return systemUser; } }
在Controller中没有引用任何userRepository,但是在请求的时候,systemUser是我们数据库中的值。
@EnableSpringDataWebSupport这个注解注入的DomainClassConverter组件,帮我们解决通过了让Spring MVC path变量转换成id类型域类,最终通过调用访问实例,达到了userRepository.findOne(id)的效果
HandlerMethodArgumentResolvers 可分页和排序
@EnableSpringDataWebSupport注解帮我们注册好了PageableHandlerMethodArgumentResolver的实例和SortHandlerMethodArgumentResolver的实例
注册使得Pageable和Sort称为有效的控制器方法参数
@RestController @RequestMapping("/user") public class SystemUserController { @Autowired private UserRepository userRepository; /** * 分页参数说明: * page :你想要查找的第几页,默认是 0 * size :分页大小,默认 20 */ @GetMapping("/page") public Page<SystemUser> findAllByPage(Pageable pageable){ return this.userRepository.findAll(pageable); } /** * * 排序参数说明: * sort: 格式为 property,property(ASC|DESC) 默认为升序排序, * 例子: * 1. sort=uname * 2. sort=uname,asc * 3. sort=uname&sort=email,desc * */ @GetMapping("sort") public HttpEntity<List<SystemUser>> findAllBySort(Sort sort){ return new HttpEntity<>(this.userRepository.findAll(sort)); } }
分页返回的JSON格式:
{ "content": [ { "id": 1, "createUserId": null, "createTime": 1605946032000, "lastModifiedUserId": null, "lastModifiedTime": null, "uname": "zhangsan", "email": "123@123.123", "address": "家住123", "version": null } ], "pageable": { "sort": { "sorted": false, "unsorted": true, "empty": true }, "pageNumber": 0, "pageSize": 20, "offset": 0, "paged": true, "unpaged": false }, "last": true, "totalPages": 1, "totalElements": 6, "first": true, "sort": { "sorted": false, "unsorted": true, "empty": true }, "size": 20, "number": 0, "numberOfElements": 6, "empty": false }
@PageableDefault改变page和size参数的默认值
@GetMapping("/page")
public Page<SystemUser> findAllByPage(@PageableDefault(page = 12,size = 40) Pageable pageable) {
return this.userRepository.findAll(pageable);
}
以上的这些类都存在于 spring-data-commonde.jar 中,由于微服务的整个环境可能采用RPC协议,所以只要对外引用这一个包即可

浙公网安备 33010602011771号