MappedSuperclass
我们对许多实体 Bean 使用 @MappedSuperclass
来获取通用属性。
使用 @Id
、@Version
和 @WhenModified
属性的映射超类很常见,如下面的示例所示,并且映射超类扩展 Model 也很常见。
package org.example.domain;
import io.ebean.Model;
import io.ebean.annotation.WhenCreated;
import io.ebean.annotation.WhenModified;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import java.time.Instant;
/**
* Base domain object with Id, version, whenCreated and whenModified.
*/
@MappedSuperclass
public abstract class BaseDomain extends Model {
@Id
long id;
@Version
Long version;
@WhenCreated
Instant whenCreated;
@WhenModified
Instant whenModified;
// getters and setters
...
}
package org.example.domain
import io.ebean.annotation.WhenCreated
import io.ebean.annotation.WhenModified
import java.time.Instant
import javax.persistence.Id
import javax.persistence.MappedSuperclass
import javax.persistence.Version
@MappedSuperclass
open class BaseDomain : Model() {
@Id
var id: Long = 0
@Version
var version: Long = 0
@WhenModified
lateinit var whenModified: Instant
@WhenCreated
lateinit var whenCreated: Instant
}
然后,我们的实体 Bean 扩展它来继承通用属性。
Customer 扩展 BaseDomain
...
@Entity
public class Customer extends BaseDomain {
String name;
LocalDate registered;
...
package org.example.domain
import javax.persistence.Entity
@Entity
class Customer : BaseDomain() {
var name: String? = null
}
Kotlin 有多种构造函数样式。有关实体 Bean 的首选构造函数样式的更多信息,请参阅 此处。