Chad
Chad

Reputation: 2071

Spring Data Rest: Tracking data changes in history tables

I would like to track changes to my data using history tables using Spring Data Rest. My expected behavior is that for each transaction that changes data, an entry would automatically added to my history table. I am not sure, but I don't think it is valid to have transactions that span multiple requests when using services.

I currently have 2 options for this:

1) Use database triggers for the data - the disadvantage I see here is that currently, most of our manipulation is done through Java, and I don't see any way to do this via Java.

2) Use Annotated event handlers - we would create event handlers for each event for each table, to track the history, I am inclined to do this, but I am not sure if this is the correct way.

Which of the 2 options are better? Are there other options available as well?

Upvotes: 0

Views: 5658

Answers (3)

dimirsen Z
dimirsen Z

Reputation: 891

Audit of operations with Envers official site

Upvotes: 2

Neeraj Verma
Neeraj Verma

Reputation: 330

I know I am answering this years later but here is another approach:

Create a RepositoryEventHandler

@Component
@RepositoryEventHandler(Code.class)
public class CodesEventHandler {

    @Autowired
    private CodesRepository repository;

    @HandleBeforeSave
    public void handleBeforeSave(Code c) {
        // backup the existing data to history (happens to be on the same table)
        Code newC = new Code();
        BeanUtils.copyProperties(c, newC);
        CodeId newId = new CodeId();
        BeanUtils.copyProperties(c.getCodeId(), newId);
        newC.setCodeId(newId);
        Date now = new Date();
        newC.getCodeId().setValidToTs(now);
        repository.save(newC);

        c.setValidFromTs(now);

    }

    @HandleBeforeDelete
    public void handleBeforeDelete(Code c) {
        // same as above but this time set the end timestamp to be now
    }
}

Upvotes: 1

Stackee007
Stackee007

Reputation: 3244

With Spring Data Rest you have an option to use events do any any pre and post processing. I believe the original transaction boundary applies to any database operations in these events.

Upvotes: 4

Related Questions