본문 바로가기

Springboot

[Springboot] DB 데이터 생성/수정 날짜(시간) 자동 처리하기

목표

  • 엔티티 관련 작업을 하다보면, 데이터의 등록 시간과 수정 시간을 자동으로 추가하고 변경해야 하는 칼럼 존재
  • 개발자가 직접 개발하지 말고 어노테이션으로 해결하자!

BaseEntity 클래스 생성

  • BaseEntity는 엔티티 객체 생성과 수정 시간을 자동으로 관리해주는 역할
@MappedSuperclass // 테이블로 생성되지 않음
@EntityListeners(value = {AuditingEntityListener.class }) // JPA 내부에서 엔티티 객체의 생성과 변경을 감지
@Getter
public class BaseEntity {
    
    @CreatedDate // 생성 날짜 (시간) 처리
    @Column(name = "regdate", updatable = false) // 객체를 DB에 반영할 때 칼럼값 변경 X
    private LocalDateTime regDate;

    @LastModifiedDate // 수정 날짜 (시간) 처리
    @Column(name = "moddate")
    private LocalDateTime modDate;

}

@MappedSuperclass

  • 해당 클래스를 테이블로 생성하지 않음
  • 그러나 클래스 A가 @MappedSuperclass이 붙은 클래스 B를 상속했을 경우, 클래스 B의 칼럼은 클래스 A의 칼럼으로 추가됨

@MappedSuperclass 클래스를 상속한 예

public class Board extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String title;

    private String content;
}
  • DB에 BaseEntity 테이블은 생성되지 않음
  • 그러나 Board 테이블에 regDate 칼럼과 modDate 칼럼이 추가됨

AuditingEntityListener

  • JPA 내부에서 엔티티 객체가 생성 / 변경되는 것을 감지
  • 이를 통해 regDate와 modDate에 적절한 값이 지정
  • 해당 리스너를 사용하기 위해서는 Application 클래스에 @EnableJpaAuditing를 추가해야 함
@EntityListeners(value = {AuditingEntityListener.class })

Application

@SpringBootApplication
@EnableJpaAuditing // 추가
public class BoardApplication {

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

}