새소식

xub2의 개발 새발 🐾
💽 Database/JPA

[JPA] 연관관계 고급 매핑 - 2 : @MappedSuperclass

2025. 9. 16. 15:40

  • -

@MappedSuperclass

클래스를 생성할 때마다 id 나 name 처럼 중복되는 필드를 쉽게 처리하고 싶다면 어떤 방법이 있을까?

즉, DB는 유지하고 객체의 필드만 메서드처럼 공통으로 묶어두고 가져다 사용하는 방법은 없을까?

이럴 때 사용하는 방법이 @MappedSuperclass을 사용하는 것이다.

적용

@MappedSuperclass
@Getter @Setter
public class BaseEntity {

    private String createdBy;
    private LocalDateTime localDateTime;
    private String lastModifiedBy;
    private LocalDateTime getLastModifiedDate;
}

먼저 공통 로직을 하나의 클래스에 모아둔다.

 

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

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

    private String name;

    @OneToMany(mappedBy = "team") // 저는 team 컬럼에 의해 관리되는 필드입니다.
    private List<Member> members = new ArrayList<>();

}

이후 생성한 BaseEntity를 상속받기만 하면 된다.

 

테스트코드 작성

실제 DB에도 위 Team 엔티티의 필드가 적용되는지 확인해보자.

예외따윈 가볍게 무시

예외는 내가 실수로 테이블 이름을 order 에약어로 설정해서 그렇다ㅋㅋ..

@Test
public void super_class_test() throws Exception {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try{

        Team team = new Team();
        team.setName("team");
        team.setCreatedBy("이게 팀이야");
        team.setCreatedDate(LocalDateTime.now());

        em.persist(team);

        em.flush();
        em.clear();

        em.find(Team.class, team.getId());

        tx.commit();

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

테스트도 끗 !


정리

이건 테이블이나 엔티티와 관련이 없고, 단순히 공통으로 사용하는 매핑 정보를 모아놓고 사용하귀 위한 기능이다.

그래서 em.find 등으로 검색할 수 없고 테이블도 생성되지 않는다.

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.