1

I have a requirement by which I have to detect and save field-level deltas between the last saved and new changes of an entity class, which is modified through a JSF front end. IOW, the form, entity class, and the DB table may have X number of fields and on every save, anywhere between 0 and X can be changed. I need to find on every save all the ones that have changes and log them somewhere for audit purposes.

At first I thought of modifying each setter:

@Transient
private Set<String> changes;

...

public void setSomeField(String _newval) {

    if(!_newval.equals(this.someField)){
        this.changes.add("SOME_FIELD");
    }

    this.someField = _newval;
}

which would require this non-elegant delta detection logic to be implemented in each setter and I don't like it. Is there an easy way to diff the new state from the persisted state using some JPA function that would give me a listing of all the fields changes and that I can then dump into my audit log storage?

amphibient
  • 29,770
  • 54
  • 146
  • 240

1 Answers1

0

Sounds like a perfect fit an interceptor in combination with an annotation. Create one, annotate the entity (classlevel would be great, but method level (setters) would be acceptible I think) and all work is done automagically. What and when you do log the results is up to you, but that could be in an entitylistener.

But why not use Envers it does excately all this (afaik jpa implementation independent)

Kukeltje
  • 12,223
  • 4
  • 24
  • 47
  • can you provide some code samples how this should be done? i have not used interceptors before (I'm assuming it is something like an aspect) – amphibient Feb 25 '15 at 22:48
  • Yes, it is 'like aspects'. But I edited my answer with a reference to what I once wanted to use. And an example (a lot more than one) of how to create interceptors can be via google (bet stackoverflow has some to) – Kukeltje Feb 25 '15 at 22:51
  • Small introductory example of a modern interceptor http://tomee.apache.org/examples-trunk/simple-cdi-interceptor/README.htm – Kukeltje Feb 25 '15 at 23:08
  • Must it be generic jpa? – Kukeltje Feb 26 '15 at 00:09