0

In order to save a Spring Data Rest object with a foreign key to another object I can use a following JSON

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

where department is a HAL link.

I wish to do some processing before the student is saved, without changing the default Spring Data Rest API.

How can I define a Spring controller endpoint so that it parses the resource link automatically and initializes the student object with the according department object?

1 Answer 1

1

Either write an 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
  }
}

or write an Annotated Handler

@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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'm aware of this option, but it seems to be a bit constrained. I would like to have access to the request context and to be able to return a custom response, and put the logic in the controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.