从 Kotlin 中带有 Jpa 注释的基类继承父属性



我们所有的JPA实体都有一个@Id,@UpdateTimestamp,乐观锁定等...我的想法是创建某种基类女巫,其中包含每个 JPA 实体需要拥有的所有内容,这些实体可以被所有人继承。

open class JpaEntity (
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id : Long? = null,
@UpdateTimestamp
var lastUpdate : LocalDateTime? = null
...
)

我试图找到如何使用这个类(或任何其他解决方案),以便我们团队中的开发人员不需要一遍又一遍地重做相同的类型。

到目前为止,根据 JPA 我的实现没有"标识符">

@Entity
class Car (
@get:NotEmpty
@Column(unique = true)
val name : String
) : JpaEntity()

有没有人对此有优雅的解决方案?

您可以像在 Java 中一样为其他实体创建基类(例如使用@MappedSuperclass):

@MappedSuperclass
abstract class BaseEntity<T>(
@Id private val id: T
) : Persistable<T> {
@Version
private val version: Long? = null
@field:CreationTimestamp
val createdAt: Instant? = null
@field:UpdateTimestamp
val updatedAt: Instant? = null
override fun getId(): T {
return id
}
override fun isNew(): Boolean {
return version == null
}
override fun toString(): String {
return "BaseEntity(id=$id, version=$version, createdAt=$createdAt, updatedAt=$updatedAt, isNew=$isNew)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BaseEntity<*>
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id?.hashCode() ?: 0
}
}
@Entity
data class Model(
val value: String
) : BaseEntity<UUID>(UUID.randomUUID()) { 
override fun toString(): String {
return "Model(value=$value, ${super.toString()})"
}
}

请参阅我的工作示例。

注意@field注释 - 没有它,CreationTimestamp/UpdateTimestamp不起作用。

您需要用@Entity @Inheritance(strategy = ...)@MappedSuperclass注释JpaEntity。第二个似乎更适合您的情况,但请参阅文档(或 https://en.wikibooks.org/wiki/Java_Persistence/Inheritance)。

Kotlin(除了可能需要指定像get:这样的注释目标)和使用Spring Boot在这里都不应该有任何区别。

最新更新