728x90
공통 매핑 정보가 필요할 때 사용할 수 있다.
MappedSuperclass 어노테이션이 적용된 클래스는 엔티티로 직접 매핑되지 않으며, 데이터베이스 테이블로 생성되지 않는다. 대신, MappedSuperclass 어노테이션이 적용된 클래스를 상속하는 하위 클래스에서 해당 클래스의 속성과 매핑 정보를 상속받아 사용할 수 있다.
MappedSuperclass로 지정된 클래스는 공통적으로 사용되는 속성이나 매핑 설정을 정의할 수 있다. 예를 들어, 여러 엔티티 클래스에서 공통적으로 사용되는 생성일자(createdDate)와 수정일자(modifiedDate)를 MappedSuperclass 클래스에 정의하고, 해당 클래스를 상속받는 엔티티 클래스에서는 추가적인 속성만 정의하여 사용할 수 있다.
MappedSuperclass를 사용함으로써 코드 중복을 줄일 수 있고, 공통 속성의 매핑 설정을 한 곳에서 관리할 수 있어 유지보수성이 향상된다. 또한, 엔티티 간의 상속 관계가 아니기 때문에 단순히 공통 속성을 상속받는 용도로 사용할 수 있다.
@MappedSuperclass
public abstract class BaseEntity {
@Column(name = "created_date")
private LocalDateTime createdDate;
@Column(name = "modified_date")
private LocalDateTime modifiedDate;
}
예를들어, 여러 엔티티들에 필요한 createdDate와 modifiedDate를 따로 BaseEntity에 작성해둔다.
@MappedSuperclass어노테이션을 추가해야한다.
@Entity
@Table(name = "employees")
public class Employee extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
}
@Entity
@Table(name = "customers")
public class Customer extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
}
이후, BaseEntity의 속성을 필요로하는 다른 엔티티들에서 BaseEntity를 extends하면 된다.
728x90
댓글