Skip to main content

MappedSuperclass

Basic Usage

org.babyfish.jimmer.sql.MappedSuperclass is used to provide abstract super types that can be inherited by entities.

The super type itself is not an entity, but can be inherited by multiple entity types to avoid duplicate declaration of the same properties in multiple entities.

Let's look at an example. First define the super type:

BaseEntity.java
@MappedSuperclass
public interface BaseEntity {

LocalDateTime createdTime();

@ManyToOne
User createdBy();

LocalDateTime modifiedTime();

@ManyToOne
User modifiedBy();
}

Other entities can inherit it:

  • BookStore

    BookStore.java
    @Entity
    public interface BookStore extends BaseEntity {

    ...Omit other code...
    }
  • Book

    Book.java
    @Entity
    public interface Book extends BaseEntity {

    ...Omit other code...
    }
  • Author

    Author.java
    @Entity
    public interface Author extends BaseEntity {

    ...Omit other code...
    }

Multiple Inheritance

Types decorated with MappedSuperclass support multiple inheritance. Other types can inherit from multiple MappedSuperclass super types.

Add a new abstract interface TenantAware to be inherited by all multi-tenant entities:

TenantAware.java
@MappedSuperclass  
public interface TenantAware {

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

...Omit other code...
}

Modify Book to inherit not only BaseEntity but also TenantAware.

tip

The role of @MapperSuperclass is not just to reduce duplicate code, it can also cooperate with two other functions:

When used in cooperation with them, multiple inheritance can provide good flexibility.