Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
Volodymyr Levytskyi Avatar asked Apr 06 '15 14:04

Volodymyr Levytskyi


2 Answers

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.

like image 164
user1686407 Avatar answered Oct 24 '22 21:10

user1686407


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

like image 39
Oliver Drotbohm Avatar answered Oct 24 '22 20:10

Oliver Drotbohm