S
S
Sergey Litvinov2019-12-07 01:20:46
Java
Sergey Litvinov, 2019-12-07 01:20:46

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;

The User object is valid. But not persistent, as a result of which, when trying to write to the database, a sheet falls out, motivated by the fact that object references an unsaved transient instance.
I understand it, but nevertheless, where should I save the transient instance (and how, is it really possible to load the UserRepo) when it is written just with @PrePersist?
How to solve this problem?
P. S On the Internet they write about CascadeType.ALL, but that's not it, because my User does not depend on the domain

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Litvinov, 2019-12-11
@SeApps

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());
    }

M
Mikhail Ketov, 2019-12-07
@Dugayoyo

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));
    }
}

also, don't forget to make columns for createBy or createAt non-editable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question