How can I convert an Object to a JSON reperesentation using Spring Data REST outside of RestController?

51 Views Asked by At

I have a project based on Spring Data REST for providing an API to interact with a database. I am using also an EntityListener to handle the update callbacks to all the entities of the project. In this listener I want to store a JSON containing the object being updated, as in the following code:

    public class listenerHandler {
    
    @PostPersist
    @PostUpdate
    @PostRemove
    private void afterAnyUpdate(Object object) {
        // Store the object as a JSON ...
        EntityModel<Object> entityModel = EntityModel.of(object);
        System.out.println(new ObjectMapper().writeValueAsString(entityModel));
    }

For this I would like to use the same conversion Spring Data REST is doing automagically when returning an EntityModel in a @RestController method, but I cannot achieve it. One of the reasons is also that when using bidirectional references, the previous code throws an error for infinity recursion, while the Spring Data REST handles it smooth with proper references.

Is there any way I can use the same conversion of Spring Data REST in the EventListener?

0

There are 0 best solutions below