테이블 설계 시 공통 요소가 존재합니다.
@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();
}
}
'항해99' 카테고리의 다른 글
항해99 36일차 TIL1 - SOP (0) | 2023.01.17 |
---|---|
항해99 35일차 TIL1 - @Data는 왜 지양해야할까? (0) | 2023.01.16 |
항해99 33일차 TIL1 - SQL을 배워야 하는 이유 (0) | 2023.01.15 |
항해99 32일차 TIL1 - DefaultHandlerExceptionResolver, BindingResult (0) | 2023.01.11 |
항해99 31일차 TIL1 스프링 심화 주차 코드 리뷰 (0) | 2023.01.10 |