跳到主要内容

MappedSuperclass

基本使用

org.babyfish.jimmer.sql.MappedSuperclass用于提供可供实体继承的抽象超类型。

该超类型并不是实体,但可以被多个实体类型继承,从而避免多个实体重复声明相同的属性。

让我们来看一个例子,先定义超类型

BaseEntity.java
@MappedSuperclass
public interface BaseEntity {

LocalDateTime createdTime();

@ManyToOne
User createdBy();

LocalDateTime modifiedTime();

@ManyToOne
User modifiedBy();
}

其他实体就可以继承它

  • BookStore

    BookStore.java
    @Entity
    public interface BookStore extends BaseEntity {

    ...省略其他代码...
    }
  • Book

    Book.java
    @Entity
    public interface Book extends BaseEntity {

    ...省略其他代码...
    }
  • Author

    Author.java
    @Entity
    public interface Author extends BaseEntity {

    ...省略其他代码...
    }

多继承

MappedSuperclass修饰的类型支持多继承,其他类型可以从多个MappedSuperclass超类型继承。

添加一个新的抽象接口TenantAware,所有支持多租户的实体都继承它

TenantAware.java
@MappedSuperclass
public interface TenantAware {

String tenant();
}
Book.java
@Entity
public interface Book extends BaseEntity, TenantAware {

...省略其他代码...
}

修改Book,让它不光继承BaseEntty,还继承TenantAware

提示

@MapperSuperclass的作用不仅仅是减少重复代码,还可以和其他另外两个功能配合使用

在和它们配合使用时,多继承可以获得良好的灵活性。