I have class structure something like:
@Entity
@Data
@Table(name="person_dtl")
@Audited
@AuditTable(value="h$person_dtl")
public class Person extends AuditBaseEntity implements Serializable {
@Id
@Column(name="person_ID", nullable = false)
private String personID;
@Column(name="person_Name", nullable = false)
private String personName;
}
@Audited
@MappedSuperClass
@EntityListeners(AuditingEntityListener.class)
public abstract class AuditBaseEntity extends BaseEntity {
@Column(name = "created_by", nullable = false, updatable = false)
@CreatedBy
protected String createdBy;
@Column(name = "last_modified_by")
@LastModifiedBy
private String lastModifiedBy;
@Column(name = "created_date", nullable = false, updatable = false)
@CreatedDate
protected Date createdDate;
@Column(name = "last_modified_date")
@LastModifiedDate
private Date lastModifiedDate;
@PrePersist
public void onPrePersist() {
this.activeIndicator="A";
}
@PreRemove
public void onPreRemove() {
this.activeIndicator="I";
}
}
@Audited
@MappedSuperClass
public abstract class BaseEntity {
@Column(name = "active_ind", nullable = false)
@CreatedBy
protected String activeIndicator;
}
I've been using hibernate envers to for auditing purpose in my spring-boot app. I have included spring-data-jpa and envers dependency in pom. I am explicitly setting values of createdBy and lastModifiedBy columns to user's id but whenever the insert is happening createdBy and lastModifiedBy column values are being set to "API" in the table in our Oracle DB. Also whenever I am performing update lastModifiedBy column value is being set to "API" even though I have set userid in my entity. Why is this happening? Am I missing some property value?
CodePudding user response:
Since you are using Spring Data, entities annotated with @CreatedBy @LastModifiedBy are going to be populated with the currently logged user.
You can override this behaviour and tell Spring to store current user id whenever you insert new record in database. To achieve that you will need to provide an implementation of AuditorAware interface and override getCurrentAuditor() method. Inside getCurrentAuditor() you will need to fetch currently logged in user 's id.
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
MyUserDetails customUser = (MyUserDetails)authentication.getPrincipal();
int userId = customUser.getUserId();
return String.valueOf(userId);
}
}
