Answer the question
In order to leave comments, you need to log in
How to work with @CreatedBy in Spring?
Good day (although it's already night) I
use Auditing. The domain has:
@ManyToOne
@JoinColumn
@CreatedBy
private User user;
Answer the question
In order to leave comments, you need to log in
I found a solution.
The fact is that I getCurrentUser()
returned the newly created User object, but I had to pull it from the database using the repo (so that the object would immediately be persisted, not detached).
Mine getCurrentUser()
now:
@Override
public Optional<User> getCurrentAuditor() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) auth.getPrincipal();
return this.userRepository.findByLogin(userDetails.getUsername());
}
You need to write a component that will return you the current logged in user from the context.
To do this, you need to create a new component that implements the AuditorAware interface.
More or less like this:
@Component
public class UserAuditorAware implements AuditorAware<User> {
@Override
public Optional<User> getCurrentAuditor() {
SecurityContext context = SecurityContextHolder.getContext();
// из контекста получаете userId или его имя, смотря что там храните.
Long userId = //;
return Optional.of(new User(userId));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question