본문 바로가기
JAVA

JPA - Auditing 과 상속을 통한 공통 속성 공통화

by HCastle 2022. 3. 16.
반응형

Auditing 기능은 엔티티가 저장 또는 수정될 때 자동으로 등록일, 등록자, 수정일, 수정자를 입력해 준다.

이 기능을 공통 속성 Entity 를 만들어 상속받아 사용하면

공통 속성에 대한 개발 비용을 단축할 수 있다.

 

아래 파일을 생성하여 현재 로그인한 사용자의 정보를 등록자와 수정자로 지정해 줄 수 있다.

 

- AuditorAwareImpl.java

import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

public class AuditorAwareImpl implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = "";
        if(authentication != null) {
            // 현재 로그인한 사용자의 정보를 조회하여 사용자의 이름을 등록자와 수정자로 지정한다.
            userId = authentication.getName();
        }

        return Optional.of(userId);
    }
}

 

- AuditConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@Configuration
@EnableJpaAuditing // JPA Audit 기능을 활성화한다.
public class AuditConfig {

    @Bean
    // 등록자와 수정자를 처리해주는 AuditorAware 을 빈으로 등록한다.
    public AuditorAware<String> auditorProvider() {
        return new AuditorAwareImpl();
    }
}

 

공통 속성 Entity 를 생성하여 상속받을 수 있도록 합니다.

 

- BaseEntity.java

import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;

@EntityListeners(value = {AuditingEntityListener.class}) // Auditing 을 적용하기 위한 annotation
@MappedSuperclass // 공통 매핑 정보가 필요할 때 사용하는 annotation. 부모 클래스를 상속 받는 자식 클래스의 매핑정보만 제공
@Data
public abstract class BaseEntity {

    @CreatedBy
    @Column(updatable = false)
    private String createdBy;

    @CreatedDate // 엔티티가 생성되어 저장될 때 시간을 자동으로 저장
    @Column(updatable = false)
    private LocalDateTime regTime;

    @LastModifiedBy
    private String modifiedBy;

    @LastModifiedDate // 엔티티의 값을 변경할 때 시간을 자동으로 저장
    private LocalDateTime updateTime;
}

 

공통 속성 Entity 를 상속받아 사용합니다.

@Entity
@Table(name = "item")
@Data
public class Item extends BaseEntity {
	..............
}

 

반응형

댓글