MappedSuperclass
基本使用
org.babyfish.jimmer.sql.MappedSuperclass
用于提供可供实体继承的抽象超类型。
该超类型并不是实体,但可以被多个实体类型继承,从而避免多个实体重复声明相同的属性。
让我们来看一个例子,先定义超类型
- Java
- Kotlin
BaseEntity.java
@MappedSuperclass
public interface BaseEntity {
LocalDateTime createdTime();
@ManyToOne
User createdBy();
LocalDateTime modifiedTime();
@ManyToOne
User modifiedBy();
}
BaseEntity.kt
@MappedSuperclass
interface BaseEntity {
val createdTime: LocalDateTime
@ManyToOne
val createdBy: User
val modifiedTime: LocalDateTime
@ManyToOne
val modifiedBy: User
}
其他实体就可以继承它
-
BookStore
- Java
- Kotlin
BookStore.java@Entity
public interface BookStore extends BaseEntity {
...省略其他代码...
}BookStore.kt@Entity
interface BookStore : BaseEntity {
...省略其他代码...
} -
Book
- Java
- Kotlin
Book.java@Entity
public interface Book extends BaseEntity {
...省略其他代码...
}Book.kt@Entity
interface Book : BaseEntity {
...省略其他代码...
} -
Author
- Java
- Kotlin
Author.java@Entity
public interface Author extends BaseEntity {
...省略其他代码...
}Author.kt@Entity
interface Author : BaseEntity {
...省略其他代码...
}
多继承
被MappedSuperclass
修饰的类型支持多继承,其他类型可以从多个MappedSuperclass
超类型继承。
添加一个新的抽象接口TenantAware
,所有支持多租户的实体都继承它
- Java
- Kotlin
TenantAware.java
@MappedSuperclass
public interface TenantAware {
String tenant();
}
TenantAware.kt
@MappedSuperclass
interface TenantAware {
val tenant: String
}
- Java
- Kotlin
Book.java
@Entity
public interface Book extends BaseEntity, TenantAware {
...省略其他代码...
}
Book.kt
@Entity
interface Book : BaseEntity, TenantAware {
...省略其他代码...
}
修改Book
,让它不光继承BaseEntity
,还继承TenantAware