Hibernate audit log of fields' change

m Lotfizad :

How can I log the changes of the entity into log files? Consider I have Person like this.

import org.hibernate.envers.Audited;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Column;

@Entity
@Audited
public class Person {
    @Id
    @GeneratedValue
    private int id;

    private String name;
    private String surname;
// add getters, setters, constructors, equals and hashCode here
}

and a code of changing existing Person

Person p1 = new Person("name-1", "surname-1");
personRepository.save(p1);
Person p2 = personRepository.findOne(1L);
p2.setName("new-name");
personRepository.save(p2);

How can I have

  • old entity
  • new entity
  • list of fields changed (some thing like Diffable's result)

In my log file? I know that envars can store changes in db and let me extract them later with AuditReader but I like to store changes in Json file to send them to third party applications (like Elastic).

sairamch04 :

You could write a custom interceptor by implementing org.hibernate.EmptyInterceptor. This has callbacks to update/insert/delete with old and new snapshots of entities.

Refer this article for more details

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=106823&siteId=1