[Spring] MappedSuperclass 사용하기

2024. 2. 14. 18:08·Framework/SpringBoot
MappedSuperclass에 대해 정리한 글입니다.

 

@MappedSuperclass란

@MappedSuperclass는 JPA에서 엔티티 클래스들 간에 공통된 매핑 정보를 재사용하기 위한 어노테이션입니다. 

이 어노테이션을 사용하면 여러 엔티티 클래스에서 동일한 매핑 정보를 공유하여 코드의 중복을 줄여줍니다.

 

가령 createdAt, updatedAt 등 모든 엔티티에 공통적으로 포함되는 필드가 있다면 @MappedSuperclass를 이용하여 공통된 필드를 포함하는 클래스를 다른 엔티티들이 상속받도록 하면 됩니다.

 

@MappedSuperclass 사용

아래 BaseEntity가 @MappedSuperclass로 지정되어있습니다.

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;

@MappedSuperclass
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {

    @Column(nullable = false, columnDefinition = "TINYINT DEFAULT 0")
    private Integer isDeleted;

    @CreatedDate
    private LocalDateTime createdAt;

    @LastModifiedDate
    private LocalDateTime updatedAt;
}

 

BaseEntity를 상속받는 User 엔티티입니다.

import jakarta.persistence.*;

@Entity
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class User extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(unique = true)
    private String email;

    @Column(nullable = false)
    private String password;

}

 

User는 BaseEntity를 상속받았기 때문에 BaseEntity의 칼럼을 모두 가지게 됩니다.

데이터베이스에서도 User는 isDeleted, createdAt, updatedAt 필드를 포함하고 있습니다.

 

알아둬야 할 점

기본적으로 MappedSuperclass로 지정된 클래스는 테이블로 매핑되지 않습니다. 

즉, MappedSuperclass로 지정된 클래스는 엔티티가 아닙니다.

 

대신, 이 클래스의 필드와 매핑 정보는 하위 엔티티 클래스에 상속됩니다.

 

그렇기 때문에 MappedSuperclass로 지정된 클래스는 추상 클래스로 정의하는 것이 좋습니다.

 


 

 

'Framework > SpringBoot' 카테고리의 다른 글

[SpringBoot3] 엔티티 상속관계에서 @Builder 적용  (0) 2024.03.20
[SpringBoot] application.properties에서 DB 정보 등 민감한 내용 분리하기  (0) 2024.03.13
[SpringBoot] 데이터베이스 스키마 자동 생성 옵션에 대해 알아보자 / spring.jpa.hibernate.ddl-auto  (0) 2023.12.26
[SpringBoot] created_at 처럼 엔티티 생성할 때 현재 날짜를 디폴트 값으로 지정하기 + 수정일 / Spring Data JPA automatic date creation  (0) 2023.12.24
[SpringBoot] 스프링 부트 data.sql이 실행되지 않을 때 (data.sql not working)  (0) 2023.12.24
'Framework/SpringBoot' 카테고리의 다른 글
  • [SpringBoot3] 엔티티 상속관계에서 @Builder 적용
  • [SpringBoot] application.properties에서 DB 정보 등 민감한 내용 분리하기
  • [SpringBoot] 데이터베이스 스키마 자동 생성 옵션에 대해 알아보자 / spring.jpa.hibernate.ddl-auto
  • [SpringBoot] created_at 처럼 엔티티 생성할 때 현재 날짜를 디폴트 값으로 지정하기 + 수정일 / Spring Data JPA automatic date creation
hurlud
hurlud
나와 같은 궁금증을 가진 사람들을 위해 오늘도! 🐥
  • hurlud
    주독야독
    hurlud
  • 전체
    오늘
    어제
  • 최근 글

    • ALL (106)
      • CS (13)
      • Linux (2)
      • Deploy (7)
        • AWS (6)
        • Docker (1)
      • IDE (13)
        • IntelliJ (5)
        • Android Studio (8)
      • DB (10)
        • MySQL (6)
        • MongoDB (4)
      • Programming Language (20)
        • JavaScript (10)
        • Java (8)
        • Python (2)
      • Framework (32)
        • Node.js (6)
        • SpringBoot (17)
        • React (6)
        • NestJS (2)
      • Git | Github (4)
      • ETC (5)
      • Akka (0)
  • 링크

    • 깃허브
  • hELLO· Designed By정상우.v4.10.0
hurlud
[Spring] MappedSuperclass 사용하기
상단으로

티스토리툴바