Database ( DB )/JPA, Querydsl

[JPA] Entity Column 상속

노루아부지 2022. 4. 17. 18:13

Database 테이블을 설계하다 보면 Column이 중복되는 경우가 많습니다.

대표적으로 이력관리를 위해 사용하는 "생성한 사람, 생성일, 마지막 수정한 사람, 마지막 수정일" 등이 있습니다.

 

이렇게 중복되는 Column은 @MappedSuperclass를 사용하여 중복을 제거할 수 있습니다.

 

먼저, 부모 크래스를 만들어서 중복된 Column을 정의합니다.

import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
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;

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class CreateUpdateDomain {
 @CreatedDate
 @Column(nullable=false, updatable=false)
 private LocalDateTime createDate;

 @CreatedBy
 @Column(nullable=false, updatable=false)
 private String createUser;

 @LastModifiedDate
 @Column
 private LocalDateTime updateDate;

 @LastModifiedBy
 @Column
 private String updateUser;

}

 

 

필요한 Entity에 CreateUpdateDomain 클래스를 상속받습니다.

@Entity
public class Member extends CreateUpdateDomain {
  private String email; 
}

@Entity
public class Seller extends CreateUpdateDomain {
  private String shopName;
}
728x90
loading