I used @CreatedDate
on entity property and I see that it inserts date into db. I don't understand what is the purpose of @CreatedBy
annotation in Spring Data JPA.
In the reference documentation I read :
We provide
@CreatedBy
,@LastModifiedBy
to capture the user who created or modified the entity
But how to create and use such user?
for TL;DR
your Entity
@CreatedBy
private UUID modifyBy;
and your SecurityAuditorAware
@Component
public class SecurityAuditorAware implements AuditorAware<UUID> {
@Override
public Optional<UUID> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.empty();
}
return Optional.of(((MyCustomUser) authentication.getPrincipal()).getId());
}
}
note: you need use the same data type, I use UUID as my custom user id.
If you already made it to the reference documentation, I recommend to read two more paragraphs to find out about and how to use AuditorAware
. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With