简体   繁体   中英

Auditing Spring User Level Context Data with JPA Events @PrePersist and @PreUpdate

I have the below JPA Entity and I would like to use the @PrePersist and @PreUpdate to facilitate the setting of the lastUpdatedBy String with the current user from the Spring context, but I don't know how I can access that information from an entity level context. Any ideas?

public abstract class BaseEntity {
  private Date createdDate;
  private String lastUpdatedBy;

    @Column(name = "LAST_UPDATED_BY")
    public String getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public void setLastUpdatedBy(String lastUpdatedBy) {
        this.lastUpdatedBy = lastUpdatedBy;
    }

  @Temporal(TemporalType.TIMESTAMP)
  @Column(name="CREATED_DATE")
  public Date getCreatedDate() {
    return createdDate;
  }

  public void setCreatedDate(Date created) {
    if (created != null) {
      this.createdDate = created;
    }
  }


  @PrePersist
  protected void onCreate() {
    createdDate = new Date();
    //lastUpdatedBy =  //need to access Spring user here
  }

 @PreUpdate
    public void onUpdate() {
      updatedDate = new Date();
      //lastUpdatedBy =  //need to access Spring user here
    }

}

A solution can be the one as defined in Good way to access Spring singleton from within domain objects? to access Spring context.
In your context define a CurrentUserHolder bean defined as singleton bean accessed in @Pre/@Post functions using ApplicationContext.getBean() .
CurrentUserHolder bean contains the current user name and its value is mantained from application (can be setted after startup or after user changing).
It's a common solution in Spring-batch to pass data across steps.

Hope can help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM