본문 바로가기

Study

[내일배움캠프 TIL] 14일차 - 3. @LastModifiedBy가 동작을 안할때.

728x90
반응형

@LastModifedBy가 작동하지 않았다.

즉, 테이블의 updatedBy에 값이 들어오지 않은 것이다.

    // 4. 수정자
    @LastModifiedBy
    @Column
    private String updatedBy;

 

[문제 현상] BaseEntity에 @LastModifiedBy를 설정하고 상속받아 사용 중인데, 수정 시 updated_at(시간)은 잘 찍히지만 updated_by(사람)는 계속 null이 들어옴.

[원인 분석]

  • 시간은 시스템에서 가져오면 되지만, 수정자 정보는 스프링이 "누가 로그인했는지" 자동으로 알 수 없음.
  • JPA와 Spring Security 사이의 다리 역할을 하는 AuditorAware 설정이 없었기 때문.

[해결 방법] AuditorAware 인터페이스를 구현하여 현재 로그인한 유저의 정보를 반환하는 빈(Bean)을 등록함.

 

@Bean
public AuditorAware<String> auditorProvider() {
    return () -> {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated()) return Optional.of("system");
        return Optional.of(auth.getName());
    };
}
반응형