前言
@MappedSuperclass注解一般作为基类的注解,表眀该类是映射的超类,继承于它的子类实体在映射时会自动添加到子类实体的对应数据库表中,用于共同的属性代码复用和模型分离。
代码示例
- BaseEntity.java
import lombok.Getter;
import lombok.Setter;
import javax.persistence.MappedSuperclass;
import java.util.Date;
@Getter
@Setter
@MappedSuperclass
public abstract class BaseEntity {
private Date createTime;
private Date updateTime;
private Date deleteTime;
}
- Banner.class
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.List;
@Entity
@Getter
@Setter
public class Banner extends BaseEntity{
@Id
private Long id;
private String name;
private String description;
private String title;
private String img;
}
- BannerItem.class
@Entity
@Getter
@Setter
public class BannerItem extends BaseEntity{
@Id
private Long id;
private String img;
private String keyword;
private Short type;
private Long bannerId;
private String name;
}
- 上述代码将Banner与BannerItem中共有的属性createTime、updateTime、deleteTime抽象成BaseEntity基类,继承于它的子类Banner、BannerItem在映射时会自动添加到对应数据库表中。