Spring Data REST

SpringDataRest 是 SpringMVC 的一个扩展他可以通过少量的代码快速构建接口来访问数据库中的数据。

Getting Strated

引入依赖

SpringBoot 中添加

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

普通 Maven 项目中添加

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-rest-webmvc</artifactId>
  <version>4.3.2</version>
</dependency>

开发 repository

jpa 一样编写一个 repository 即可,DATA REST 会为我们注册一个 Resource,默认的资源名是 modelName 的复数

引入在线调试(knife4j+Swagger3)

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>
# springdoc-openapi项目配置
springdoc:
  #swagger地址
  swagger-ui:
    # http://ip:port/doc.html
    path: /swagger-ui.html
    tags-sorter: alpha
    operations-sorter: alpha
  # openapi规范的json
  api-docs:
    path: /v3/api-docs
  group-configs:
    - group: 'default'
      paths-to-match: '/**'
      packages-to-scan: com.mfyuan
# knife4j的增强配置,不需要增强可以不配
knife4j:
  enable: true
  setting:
    language: zh_cn

访问 http://localhost:8080/doc.html#/home 查看 api 文档,会发现 spring-data-rest 帮我们创建了很多 cotroller
image.png

地址请求类型请求数据类型请求参数描述
/tUsersGETapplication/x-www-form-urlencodedpage:当前页
size:分页大小分页查询
/tUsers/{id}GETapplication/x-www-form-urlencodedid:主键根据 id 查询
/tUsersPOSTapplication/json模型数据saveOrUpdate 存在就更新,不存在就新增,根据 id 查询。
/tUsers/{id}PUTapplication/jsonid:主键
请求体中放模型数据根据主键更新
/tUsers/{id}DELETEapplication/x-www-form-urlencodedid:主键根据主键删除
/tUsers/{id}PATCHapplication/jsonid:主键
请求体中放模型数据与 PUT 的区别是只更新请求体中包含的字段,而 PUT 则是不存在的字段为修改为 null

AbstractRepositoryEventListener

Spring-Data-Rest 为我们提供许多事件在持久化操作时进行扩展

  • BeforeCreateEvent:新增模型数据前
  • AfterCreateEvent:新增模型数据后
  • BeforeSaveEvent:更新模型数据前
  • AfterSaveEvent:更新模型数据后
  • BeforeLinkSaveEvent:多表关联保存的时候前 例如:OneToOne 等
  • AfterLinkSaveEvent:多表关联保存的时候后 例如:OneToOne 等
  • BeforeDeleteEvent:删除模型数据前
  • AfterDeleteEvent:删除模型数据后

@RepositoryRestResource

这个注解不是必要的,他可以指定导出的资源名称是什么样的等。如 user,默认的则是 users
{ip}:{port}/user

属性

  • path:指定导出的资源路径,默认是 model 的复数
  • collectionResourceRel:指定返回多个数据是数组的 key 名称默认的是 modelName 的复数
  • itemResourceRel:指定单个数据返回的 link 中的查询自己的 key 名称默认的是 modelName
  • exported:是否公开资源。默认为 true,为 false 不开放该资源的访问也就是不能通过 /model 接口来进行访问

image.png 1723709656041.jpg 1723709773158.jpg

自定义查询方法

@RepositoryRestResource(path = "user")
public interface UserRepository extends CrudRepository<TUser,Long>, PagingAndSortingRepository<TUser,Long> {

    
    /**
     * 通过 user/search/findTopByAge 来访问
     * @param age
     * @return
     */
    TUser findTopByAge(Long age);

    /**
     * 通过 user/search/findTopBySex 来访问
     * 可以通过@Param 来指定参数名
     * @param sex
     * @return
     */
    TUser findTopBySex(@Param("sexName") String sex);
}

image.png image.png

@RestSource

自定义导出查询方法的路径,及是否公开该查询资源等。

  • path:自定义导出查询方法的路径。默认为方法的名称。
  • rel:指定 link 中的资源名:默认为资源名
  • exported:是否公开查询方法。默认为 true,为 false 不开放该查询方法的访问也就是不能通过。
/**
 * 通过 user/search/ageTop 来访问
 * @return
 */
@RestResource(path = "ageTop")
TUser findTopByOrderByAgeDesc();

image.png

注意

自定义的这些方法都是 GET 方法

自定义配置

可以使用 RepositoryRestConfigurer,也可以通过 spring.data.rest 在配置文件中直接进行配置。

@Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {

    return new RepositoryRestConfigurer() {
        @Override
        public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
            // 默认情况下是会隐藏 id 字段的,可以通过该方法来对 id 进行暴露,这样查询的时候就能返回 id
            config.exposeIdsFor(TUser.class);
            // 设置请求路径的前缀
            config.setBasePath("/api");
            // 设置创建时不显示新增的数据
            config.setReturnBodyOnCreate(false);
            // 设置更新时不显示更新后的数据
            config.setReturnBodyOnUpdate(false);
            // 设置删除时不显示删除前的数据
            config.setReturnBodyOnDelete(false);
        }
    };
}
  • 17
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假女吖☌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值