[SpringBoot]-@MappedSuperClass

ACAI BERRY DEVELOVER·2023년 6월 25일
0
post-thumbnail

public @interface MappedSuperclass
Designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.
A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself. When applied to the subclasses the inherited mappings will apply in the context of the subclass tables. Mapping information may be overridden in such subclasses by using the AttributeOverride and AssociationOverride annotations or corresponding XML elements.

  • 자동으로 처리되는 날짜/시간을 설정

모든 클래스마다 직접 공통 필드를 작성할 수 있지만, 해당 필드를 가진 추상 클래스(혹은 일반 클래스)를 만들어 이를 다른 클래스들이 상속받도록 하는 것이 좀 더 효과적이다.공통된 필드를 사용하기 위한 상속을 받은 것이지, 부모와 자식의 관계 혹은 is-a 관계이기 때문에 상속을 받은 것이 아니다.

@MappedSuperClass

  • 상속관계 매핑이 아니다.
  • 엔티티가 아니고, 테이블과 매핑되지 않는다.
  • 부모 클래스를 상속 받는 자식 클래스에 매핑 정보만 제공한다.
  • 직접 생성해서 사용할 일이 없으므로 추상 클래스로 사용하는 것이 좋다.
  • 테이블과 관계 없고 단순히 엔티티가 공통으로 사용하는 매핑 정보를 모으는 역할이다.
  • 주로 등록일, 수정일, 등록한 사람, 수정한 사람 같은 전체 엔티티에서 공통으로 적용하는 정보를 모을 때 사용한다.
  • 실제 테이블은 해당 클래스를 상속한 엔티티의 클래스로 데이터베이스 테이블이 생성된다.
  • BaseEntityClass
package com.example.demo.Entity;

import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
@Getter
abstract class BaseEntity {

    @CreatedDate
    @Column(name ="regdate", updatable = false)
    private LocalDateTime regDate;

    @LastModifiedDate
    @Column(name="moddate")
    private LocalDateTime modDate;
}

reference: https://velog.io/@rudwnd33/JPA-MappedSuperclass-vs-Embedded-Type
https://ttl-blog.tistory.com/132

profile
쓸때 대충 쓰지 말고! 공부하면서 써!

0개의 댓글