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:
- Java
- Kotlin
@MappedSuperclass
public interface BaseEntity {
LocalDateTime createdTime();
@ManyToOne
User createdBy();
LocalDateTime modifiedTime();
@ManyToOne
User modifiedBy();
}
@MappedSuperclass
interface BaseEntity {
val createdTime: LocalDateTime
@ManyToOne
val createdBy: User
val modifiedTime: LocalDateTime
@ManyToOne
val modifiedBy: User
}
Other entities can inherit it:
-
BookStore
- Java
- Kotlin
BookStore.java@Entity
public interface BookStore extends BaseEntity {
...Omit other code...
}BookStore.kt@Entity
interface BookStore : BaseEntity {
...Omit other code...
} -
Book
- Java
- Kotlin
Book.java@Entity
public interface Book extends BaseEntity {
...Omit other code...
}Book.kt@Entity
interface Book : BaseEntity {
...Omit other code...
} -
Author
- Java
- Kotlin
Author.java@Entity
public interface Author extends BaseEntity {
...Omit other code...
}Author.kt@Entity
interface Author : 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:
- Java
- Kotlin
@MappedSuperclass
public interface TenantAware {
String tenant();
}
interface TenantAware {
val tenant: String
}
- Java
- Kotlin
@Entity
public interface Book extends BaseEntity, TenantAware {
...Omit other code...
}
@Entity
interface Book : BaseEntity, TenantAware {
...Omit other code...
}
Modify Book
to inherit not only BaseEntity
but also TenantAware
.
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.