![[JPA] 엔티티 공통 필드 상속(@MappedSuperclass)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2F7aUcA%2FbtsM6Zmep1n%2F9U0FJGLbH4OAjVISMFOlp0%2Fimg.png)
[JPA] 엔티티 공통 필드 상속(@MappedSuperclass)Back-End/JPA2025. 4. 3. 16:06
Table of Contents
@MappedSuperclass
엔티티마다 생성 날짜와 수정 날짜가 존재한다고 가정하면, 모든 엔티티에 해당 코드를 넣는 것은 비효율적이다.
따라서 아래의 코드를 통해서 공통 필드를 상속받게 할 수 있다.
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {
@CreatedDate
private LocalDateTime createdDateTime;
@LastModifiedDate
private LocalDateTime modifiedDateTime;
}
- 공통 필드(생성일시, 수정일시)를 모든 엔티티에서 자동으로 사용하고 싶을 때이 BaseEntity를 상속받아 사용하면 된다.
@MappedSuperclass
- 이 클래스는 엔티티 테이블로 직접 매핑되지 않지만,상속받는 자식 엔티티에게 필드와 매핑 정보를 전달한다.
- 즉, 상속받는 클래스가 실제 테이블을 생성할 때 created_date_time, modified_date_time 컬럼이 포함된다.
@EntityListeners(AuditingEntityListener.class)
- 스프링 JPA의 감시 리스너(Auditor)를 활성화한다.
- 이 설정이 있어야 @CreatedDate, @LastModifiedDate가 자동으로 작동한다.
- @CreatedDate: 엔티티가 처음 저장될 때 자동으로 현재 시간이 입력됨
- @LastModifiedDate : 엔티티가 수정될 때마다 자동으로 갱신
사용
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class OrderProduct extends BaseEntity { // BaseEntity 상속
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
private Order order;
@ManyToOne(fetch = FetchType.LAZY)
private Product product;
public OrderProduct(Order order, Product product) {
this.order = order;
this.product = product;
}
}
'Back-End > JPA' 카테고리의 다른 글
[JPA] @Builder.Default (0) | 2025.04.04 |
---|---|
[JPA] 엔티티 클래스에서 @Builder 위치 (0) | 2025.04.03 |
[JPA]PostgreSQL 사용시, 엔티티에 Enum 매핑 오류 (0) | 2024.11.21 |
[Spring Data JPA] Projections 과 Native Query (0) | 2024.08.16 |
[Spring Data JPA] 새로운 엔티티인지 구별하는 방법 (0) | 2024.08.15 |