Reputation: 87
When ever I create a any user that needs to be taken automatically who has created the User with the @CreatedBy annotation and when I manupulate any thing thats needs to be taken automatically with the annotation @LastModifiedBy. But this is not working now. What may be the reason?
This is my entity class
@Slf4j
@Getter
@Setter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Column(name = "created_by" , nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;
@CreatedDate
@Column(name = "created_date", updatable = false)
@JsonIgnore
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
@JsonIgnore
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
@JsonIgnore
private Instant lastModifiedDate = Instant.now();
@Transient
public <T> T getView(Class<T> viewClass) {
try {
T view = viewClass.getDeclaredConstructor().newInstance();
BeanUtils.copyProperties(this, view);
return view;
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
log.error("Error mapping model to view", e);
}
return null;
}
Upvotes: 4
Views: 9964
Reputation: 1
Add this Bean to your Main Application
@Bean
AuditorAware<String> auditorProvider() {
// override getCurrentAuditor method to provide the current user
return () -> Optional.of(SecurityContextHolder.getContext().getAuthentication().getName());
}
Upvotes: 0
Reputation: 1259
Add below annotation to your Application Class.
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
Define the bean:
@Bean
public AuditorAware<String> auditorAware(){
return new CustomAuditAware();
}
Create CustomAuditAware class:
public class CustomAuditAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return null;
}
return ((User) authentication.getPrincipal()).getUsername();
}
Upvotes: 11
Reputation: 5968
You need to create your custom class that implements AuditorAware<?>
in order to define which is your current auditor. So let's define by following code:
public class AuditingService implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of("Bhargav");
}
}
Upvotes: 1