백엔드 개발자 - 젤리곰 2024. 7. 10. 21:15
728x90

1. @MappedSuperclass 언제 사용할까?

여러 엔티티 클래스에서 공통으로 사용되는 필드를 하나의 상위 클래스에 정의하고 이를 상속받아 사용하고자 할 때.

 

만약, 엔티티를 모두 만들었는데 공통적인 필드들을 추가해야 한다면

하나 하나 엔티티마다 이렇게 중복으로 작성을 해줘야한다.

이런 작업을 하지 않도록 도와주는 애노테이션이 바로 @MappedSuperclass다.

private String createdBy;
private LocalDateTime createdDate;
private String lastModifiedBy;
private LocalDateTime lastModifiedDate;
...

 

2. 코드 예시

 

✔️공통 매핑정보를 갖는 상위 클래스(BaseEntity)와 이를 상속받는 Member 클래스

@MappedSuperclass
@Getter
@Setter
public abstract class BaseEntity {

    private String createdBy;
    private LocalDateTime createdDate;
    private String lastModifiedBy;
    private LocalDateTime lastModifiedDate;
}


@Entity
@Getter
@Setter
public class Member extends BaseEntity{

    @Id
    @GeneratedValue
    @Column(name = "MEMBER_ID")
    private Long id;

    @Column(name = "USERNAME")
    private String username;

}

 

공통 필드를 정의할 클래스를 만든다. 여기서는 BaseEntity로 만들었다.

이 클래스에 @MappedSuperclass 애노테이션을 붙여준다.

 

Member 클래스는 BaseEntity를 상속받는다. (매핑 정보를 상속받기 위함)

 

✔️main 메서드

public class JpaMain {

    public static void main(String[] args) {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();
        tx.begin();
        try{
            Member member = new Member();
            member.setUsername("userA");
            member.setCreatedBy("ururuwave");
            member.setCreatedDate(LocalDateTime.now());
            em.persist(member);

            em.flush(); //영속성컨텍스트에 있는 것을 DB로!
            em.clear(); //영속성컨텍스트를 날려서 1차캐시에 아무것도 안남긴다!

            tx.commit();
        }catch (Exception e){
            tx.rollback();
        }finally {
            em.close();
        }

    }
}

 

Member 클래스에 필드를 명시해주지 않아도 BaseEntity를 상속받았기 때문에 createdBy, createdDate, lastModifiedBy, lastModifiedDate 필드를 함께 생성하는 쿼리가 실행된다.

create table Member (
        MEMBER_ID bigint not null,
        TEAM_ID bigint,
        createdDate timestamp(6),
        lastModifiedDate timestamp(6),
        USERNAME varchar(255),
        createdBy varchar(255),
        lastModifiedBy varchar(255),
        primary key (MEMBER_ID)
    )

 

✔️데이터 베이스 확인

 

3. 정리

공통된 매핑 정보를 상위 클래스에 정의하고 여러 엔티티에서 이를 재사용함으로써 코드의 중복을 줄이고 일관성을 유지할 수 있다.

 

728x90