[JPA] AuditorAware을 사용하여 자동으로 등록/수정자 생성하기

2022. 11. 21. 15:02Web/JAVA

JPA 를 사용하다 보면 중복적으로 등록자/등록일/수정자/수정일 DB에 등록할 경우가 잦다.

AuditorAware을 구현하여  이런 중복적인 코드를 제거하고 어노테이션을 활용하여 간단하게 해경해보자.

 

1. AuditorAware 을 Implement 받는 클래스 생성

  • 로그인 시 스프링 시큐리티에 있는 로그인 정보를 받아올수 있도록 로직을 구성해준다.
public class AuditorAwareImpl implements AuditorAware<Long> {

    @Override
    public Optional<Long> getCurrentAuditor() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null == authentication || !authentication.isAuthenticated()) {
            return null;
        }
        LunaUser lunaUser = (LunaUser) authentication.getPrincipal();
        return Optional.of(lunaUser.getLunaUserNo());
    }
}

2. Config 파일 생성

@Configuration
@EnableJpaAuditing
public class AuditingConfig {
    @Bean
    public AuditorAware<Long> auditorProvider() {
        return new AuditorAwareImpl();
    }
}
  • 이렇게만 해주면 기본적인 설정은 끝이 났다고 볼수있다.
  • 이제 원하는곳에 어노테이션을 선언하여 사용하는 일만 남았다.
  • 이런식으로 Entity 컬럼에 선언해주면 등록자/등록일/수정자/수정일 이 자동으로 등록되는 것을 확인할 수 있다.