开发者

How to access oldObject and newObject with Entity listeners and Callback methods

开发者 https://www.devze.com 2023-03-07 17:38 出处:网络
I\'m logging all the changes made to my objects in the DB. @PostPersist public void logPostPersist(Object object) {

I'm logging all the changes made to my objects in the DB.

@PostPersist
public void logPostPersist(Object object) {
    PAudit p = new PAudit();
    p.setChangeType("INSERT");
    p.setObjectState(object.toString());
    p.setUserName(SecurityContextHolder.getContext().getAuthentication().getName());
    try {
        p.persist();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@PostUpdate
public开发者_如何学编程 void logUpdate(Object object) {
    PAudit p = new PAudit();
    p.setChangeType("UPDATE");
    p.setObjectState(object.toString());
    p.setUserName(SecurityContextHolder.getContext().getAuthentication().getName());
    p.persist();
}

this will give me the current state of the object after it has changed. I also want to add the previous state of the object (before it has changed) along with the current state.

How can I get the both states of the object (before change and after change) at the same time?

Thank you.


You can do this by creating an interface which your domain classes providing previous state should implement:

public interface PreviousStateProvider {
  public T getPreviousState();

  public void setPreviousState(T state);
}

The domain class should have a private property to hold the state at the point at which it was loaded.

Then you can create a Hibernate PostLoad listener which sets the loaded state on the domain object at the point that it's loaded. Then when you come to update the domain object you can access the previous (loaded) state using the:

getPreviousState()

method.

Hope this is clear.

0

精彩评论

暂无评论...
验证码 换一张
取 消