Volodymyr Levytskyi
Volodymyr Levytskyi

Reputation: 437

How does @CreatedBy work in Spring Data JPA?

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?

Upvotes: 19

Views: 44917

Answers (2)

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83081

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. :)

Upvotes: 25

min
min

Reputation: 1098

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.

Upvotes: 15

Related Questions