[jpa] entity 의 생성일, 수정일을 자동으로 설정하기

대부분의 테이블 컬럼에는 생성일과 수정일이 존재한다.

이걸 매번 entity 에 선언해서 쓰기 귀찮을때 사용하는 방법을 소개한다.

application 실행 파일에 @EnableJpaAuditing 추가
@EnableJpaAuditing
@SpringBootApplication
public class CmsApiApplication
{
...
}

부모 entitiy 수정
@Data
@MappedSuperclass
@EntityListeners( AuditingEntityListener.class )
public abstract class BaseEntity
{
	@Column( name = "created_date", nullable = false, updatable = false )
	@CreatedDate
	public LocalDateTime createdDate;

	@Column( name = "modified_date" )
	@LastModifiedDate
	public LocalDateTime modifiedDate;
}

@MappedSuperclass 추가
@EntityListeners( AuditingEntityListener.class ) 추가
생성일 변수에 @CreatedDate 추가
수정일 변수에 @LastModifiedDate 추가

save 시 @CreatedDate 동작
update 시 @LastModifiedDate 동작

Subscribe to X세대 신입사원

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe
774-86-01972 cinnabar.3d@gmail.com