본문 바로가기

항해99

항해99 34일차 TIL1 - @CreateBy, @ModifiedBy

테이블 설계 시 공통 요소가 존재합니다.

 

@MappedSuperclass는 공통 요소를 처리할 수 있는 JPA 애노테이션입니다.

@MappedSuperclass을 자바의 객체로 비교하자면 추상클래스와 유사합니다. @MappedSuperclass를 정리하자면 테이블(실제 테이블로 매핑되지 않음)과는 관계없고 단순히 엔티티가 공통으로 사용하는 매핑 정보를 모아주는 역할을 합니다.

 

이중에서도 오늘은 @CreateBy, @LastModifedBy 에 대해 알아보겠습니다.

생성자

 

1. 우선 BaseEntity를 만들고 @CreateBy, @LastModifedBy 필드를 생성합니다.

@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity {
    @CreatedBy
    private Long createBy;

    @LastModifiedBy
    private Long modifiedBy;

 

2. @CreateBy가 동작할 수 있도록 AuditorAware 구현체를 만들어주어야 합니다.

public class Auditor implements AuditorAware<Long> {

    @Override
    public Optional<Long> getCurrentAuditor() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetailsImpl) {
            Long id = ((UserDetailsImpl) principal).getMember().getId();
            return Optional.of(id);
        }

        return Optional.empty();
    }
}

 

3. AuditorAware 구현체(Auditor)를 스프링 빈으로 등록해서 DI 합니다.

@EnableJpaAuditing
@Configuration
public class JpaConfig {

    @Bean
    public AuditorAware<Long> auditorProvider() {
        return new Auditor();
    }
}