본문 바로가기

프로젝트/SpringBoot Side Project

개인프로젝트에 @CreatedBy 적용하기

인프런 김영한님의 실전! SPRING DATA JPA 강의를 듣다가 Auditing을 이용하면 자동으로 작성자 정보를 DB에 저장할 수 있다는 것을 알게 되었습니다.

실제로 개인프로젝트를 진행하면서 적용해보았는데요, @CreatedDate 어노테이션과 달리 추가 설정 정보가 더 필요했기에, 기록해보고자 합니다.

 

적용할 프로젝트 정보 : 

JDK17,

Spring Boot v3.2.0

Spring Data JPA 

Spring Security 

 

여기서는 Member엔티티와 Article엔티티를 가지고 기록해두겠습니다.

 

BaseTimeEntity와 BaseEntity를 만들어줍니다.

@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public class BaseTimeEntity {

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdDate;

    @LastModifiedDate
    private LocalDateTime lastModifiedDate;
}

 

@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public class BaseEntity extends BaseTimeEntity{
    @CreatedBy
    @Column(updatable = false)
    private String createdBy;
    @LastModifiedBy
    private String lastModifiedBy;
}

 

Member엔티티입니다.

Security 적용을 위해 UserDetails를 구현하고 있습니다.

여기에 BaseTimeEntity를 상속해서 연결해두었습니다.

@Entity @Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Member extends BaseTimeEntity implements UserDetails {
    @Id @GeneratedValue
    @Column(name = "member_id")
    private Long id;

    @Column(nullable = false, unique = true, length = 100)
    private String email;
    private String password;

    @Column(unique = true, length = 20)
    private String nickname;
    @Embedded
    private Address address;
    @Enumerated(EnumType.STRING)
    @Column(length = 8)
    private MemberStatus status;
    private String profileImg;

    @OneToMany(mappedBy = "member", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<Authorities> authorities = new ArrayList<>();

 

Article엔티티입니다.

작성자,수정자 정보를 위해 BaseEntity를 상속받았습니다.

@Entity
@Getter @NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Article extends BaseEntity{
    @Id @GeneratedValue
    @Column(name = "article_id")
    private Long id;

    @Column(nullable = false, length = 50)
    private String title;

    @Column(nullable = false, columnDefinition = "LONGTEXT")
    @Lob
    private String content;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "member_id")
    private Member member;

 

Application클래스입니다.

작성자 정보를 넣어주기 위해 AuditorAwareImpl이라는 클래스를 Bean으로 등록하고 있습니다.

@EnableJpaAuditing
@SpringBootApplication
public class BlogApplication {

    public static void main(String[] args) {
       SpringApplication.run(BlogApplication.class, args);
    }

    @Bean
    public AuditorAwareImpl auditorProvider(){
       return new AuditorAwareImpl();
    }

}

 

AuditorAwareImpl 클래스입니다. AuditorAware 인터페이스를 구현하고 있습니다.

public class AuditorAwareImpl implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(null == authentication || !authentication.isAuthenticated()){
            return null;
        }
        Object principal =  authentication.getPrincipal();
        if(principal instanceof UserDetails){
            return Optional.of(((UserDetails)principal).getUsername());
        }
        return null;
    }
}

 

AuditorAware는 제너릭이기때문에 기록하고 싶은 타입을 넣으면 됩니다.

저는 로그인시 member의 email 정보를 가지고 security 처리를 하고 있기 때문에, 작성자에도 member의 email 정보를 넣겠습니다.

 

적용 결과 로그인한 사용자가 글을 작성하면 정상적으로 data가 입력됩니다.

 

참고 : https://javacpro.tistory.com/85