Whimusical
Whimusical

Reputation: 6629

How to do a calculation on an entity in a GET/find on Spring Data Rest?

I am using @RepositoryRestResource facility,but I would like to do a calculation (depending on external service) over a transient field each time the user executes a read operation GET, find etc..

If only there was an AfterGet/AfterFind event at list I could handle the modification by extending AbstractRepositoryEventListener

Any clean suggestion?

Upvotes: 1

Views: 350

Answers (1)

Whimusical
Whimusical

Reputation: 6629

I found the way through @Alan Hay suggestion.

@Entity
@EntityListeners(TransientFieldResolver.class)
public class Entity {

    private Long id;
    private String transientField;
}

@Component
public static class TransientFieldResolver {

    private static ExternalService externalService;

    @Autowired
    public void setExternalService(ExternalService externalService) {
        TransientFieldResolver.externalService = externalService;
    }

    @PostLoad
    public void onPostLoad(final Entity entity) {
        if (Objects.isNull(entity.getTransientField())) {
            TransientFieldResolver.externalService.fillTransientField(entity);
        }
    }
}

Upvotes: 1

Related Questions