Java for Web学习笔记(一三一)映射(7)entity的抽象和继承

Mapped superclass

我们通过@javax.persistence.MappedSuperclass定义一个Mapped superclass,定义表格的通用属性,提供给Entity继承。它和Entity的属性映射是一样,但需注意:

  • entity可以重写@Column。类标记为 @AttributeOverride或@AttributeOverrides,在里面给出需要override的属性名字和新的@column定义。
  • entity不可以重写属性类型,也就是不能重写@Basic, @Lob, @Temporal,@Enumerated, @Convert

小例子

CREATE TABLE `NewsArticle` (
  `ArticleId` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `Revision` bigint(20) unsigned NOT NULL,
  `DateCreated` timestamp(6) NULL DEFAULT NULL,
  `DateModified` timestamp(6) NULL DEFAULT NULL,
  `Title` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `Content` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`ArticleId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我们将提供一个多重嵌套的模拟例子。

@MappedSuperclass

//1、由于我们使用了JPA的标记@MappedSuperclass,所以必须位于JPA可以扫描的地方,一般与entity放在一起
//2、加上abstract,表明这个类不单独使用
@MappedSuperclass
public abstract class BaseEntity {
    private long id;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long getId() { ... }
    public void setId(long id) { ... }
        this.id = id;
    }
}

多层@MappedSuperclass的嵌套:

@MappedSuperclass
public abstract class VersionedEntity extends BaseEntity{
    private long version;
     
    @Version
    @Column(name = "Revision")
    public long getVersion() { ... }
    void setVersion(long version) { ... }
}
@MappedSuperclass
public abstract class AuditedEntity extends VersionedEntity{
    private Instant dateCreated;
    private Instant dateModified;

    @Convert(converter = InstantConverter.class)
    public Instant getDateCreated() { ... }
    public void setDateCreated(Instant dateCreated) { ... }
    
    @Convert(converter = InstantConverter.class)
    public Instant getDateModified() { ... }
    public void setDateModified(Instant dateModified) { ... }
}

Entity继承Mapped Superclass

@Entity
//通过@AttributeOverride重写属性的@Column
@AttributeOverride(name="id", column=@Column(name = "ArticleId"))
public class NewsArticle extends AuditedEntity{
    private String title;
    private String content;	

    @Basic
    public String getTitle() { ...}
    public void setTitle(String title) { ... }

    @Basic
    public String getContent() { ... }
    public void setContent(String content) { ... }
}

相关链接:我的Professional Java for Web Applications相关文章

猜你喜欢

转载自blog.csdn.net/flowingflying/article/details/81391496