spring RepositoryEventHandler for link modification missing link target reference

Viewed 91

I am using a RepositoryRestController to expose REST endpoint to modify entity X which is linked to another entity Y.

class X {
    Set<Y> y_set;
}

I would like to execute some code when Ys are added or removed to an X.

class MyAction {
    // initialised somehow
    XRepository xRepo;

    public void unlinkYFromX() {
       X x = xRepo.getAnX();
       // get a Y from the ones linked to X using some logic
       Y y = x.getYs().get(0);
       x.getYs().delete(y);
       xRepo.save(x);
       // I expect the event handlers to be trigger now
       // giving me a reference to x and y 
    }

}

I am trying to define a RepositoryEventHandler with a handler function annotated with HandleBeforeLinkSave:

@RepositoryEventHandler
class XYLinkHandler {

@HandleBeforeLinkSave
 public void handleYLinkSave(X x, Object linked) {
        // do some code with the source X
        // and the newly linked Y
    }
}

The problem is that the 2nd argument of the handler function is always null. In other words it does not contain the Y I am linking.

The same phenomenon (missing linked reference) happens regardless if it a Before, After, Save or Delete event handler.

Has anyone encountered this problem? Does anyone have a solution or workaround?

Thanks.

1 Answers

The 2nd parameter, linked, is a Proxy object to the collection property. It contains the entire contents, not just the newly added (or removed) object. It could be used by casting it to a Collection and working on the collection. This, appears a buggy implementation, since the inability to know which item is added to the collection makes this event handler rather limited in its capability.

See a workaround in this response

Related