How does @CreatedBy work in Spring Data JPA?
25,256
Solution 1
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
. :)
Solution 2
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.
Author by
Volodymyr Levytskyi
Updated on April 13, 2020Comments
-
Volodymyr Levytskyi about 4 years
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 entityBut how to create and use such user?
-
Chris almost 5 yearsWhere did
MyCustomUser
come from? -
min almost 5 years@Chris it's from your custom user implement, check this