【问题标题】:Using Spring Data style HAL in Spring Data Controller在 Spring Data Controller 中使用 Spring Data 样式 HAL
【发布时间】:2021-01-14 11:09:07
【问题描述】:

为了将带有外键的 Spring Data Rest 对象保存到另一个对象,我可以使用以下 JSON

{
     "studentName":"newObj",
     "department":"departments/2"
}

其中部门是 HAL 链接。

我希望在保存学生之前进行一些处理,而不更改默认的 Spring Data Rest API。

如何定义 Spring 控制器端点,以便它自动解析资源链接并使用相应的部门对象初始化学生对象?

【问题讨论】:

    标签: spring-data-jpa spring-data-rest


    【解决方案1】:

    要么写ApplicationListener

    public class BeforeSaveEventListener extends AbstractRepositoryEventListener {
    
      @Override
      public void onBeforeSave(Object entity) {
        ... logic to handle inspecting the entity before the Repository saves it
      }
    
      @Override
      public void onAfterDelete(Object entity) {
        ... send a message that this entity has been deleted
      }
    }
    

    或者写一个带注释的处理程序

    @RepositoryEventHandler 
    public class PersonEventHandler {
    
      @HandleBeforeSave
      public void handlePersonSave(Person p) {
        // … you can now deal with Person in a type-safe way
      }
    
      @HandleBeforeSave
      public void handleProfileSave(Profile p) {
        // … you can now deal with Profile in a type-safe way
      }
    }
    

    https://docs.spring.io/spring-data/rest/docs/current/reference/html/#events

    【讨论】:

    • 谢谢。我知道这个选项,但它似乎有点受限。我希望能够访问请求上下文并能够返回自定义响应,并将逻辑放入控制器中。
    猜你喜欢
    • 1970-01-01
    • 2016-10-24
    • 2017-02-21
    • 1970-01-01
    • 2015-05-30
    • 2021-12-01
    • 1970-01-01
    • 2014-05-05
    • 2012-03-25
    相关资源
    最近更新 更多