dev/JPA 기본
@MappedSuperclass
dev_0hoon
2024. 2. 3. 18:30

예시이다. 객체를 사용하는데 계속 id,name이 모든 클래스 안에 반복적으로 들어간다. 이걸 공통으로 쓸 수는 없을까?
package jpabook.jpashop.domain;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
@MappedSuperclass
public class BaseEntity {
private String createBy;
private LocalDateTime createDate;
private String lastModifiedBy;
private LocalDateTime lastModifiedDate;
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public LocalDateTime getCreateDate() {
return createDate;
}
public void setCreateDate(LocalDateTime createDate) {
this.createDate = createDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public LocalDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(LocalDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
이렇게 넣은 다음에
@Entity
public class Member extends BaseEntity{
상속시켜서 사용하면
create table Member (
id bigint not null,
createBy varchar(255),
createDate timestamp,
lastModifiedBy varchar(255),
lastModifiedDate timestamp,
USERNAME varchar(255),
LOCKER_ID bigint,
TEAM_ID bigint,
primary key (id)
)"
쿼리에 컬럼으로 생기게 된다.
특징
- 상속관계 매핑 x
- 엔티티 x , 테이블과 매핑 x
- 부모 클래스를 상속 받는 자식 클래스에 매핑 정보만 제공
- 조회, 검색 불가(em.find(BaseEntity)불가)
- 직접 생성해서 사용할 일 없으므로 추상클래스 권장
- 테이블과 관계가 없고 , 단순히 엔티티가 공통으로 사용하는 매핑정보를 모으는 역할
- 주로 등록일, 수정일, 등록자, 수정자 등 전체 엔티티에서 공통으로 적용하는 정보를 모으는 역할
- 참고 : @Entity 클래스는 엔티티나 @MappedSuperclass로 지정한 클래스만 상속 가능