从Kotlin中具有Jpa批注的基类继承父属性

Sti*_*cke 0 jpa kotlin spring-boot

我们所有的JPA实体都有一个@ Id,@ UpdateTimestamp,乐观锁定等。我的想法是创建一种基类巫婆,其中包含每个JPA实体都需要继承的所有东西。

open class JpaEntity (

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   var id : Long? = null,

   @UpdateTimestamp
   var lastUpdate : LocalDateTime? = null

   ...
)
Run Code Online (Sandbox Code Playgroud)

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

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

@Entity
class Car (

    @get:NotEmpty
    @Column(unique = true)
    val name : String

) : JpaEntity()
Run Code Online (Sandbox Code Playgroud)

有谁对此有一个优雅的解决方案?

Cep*_*pr0 5

您可以按照与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
    }
}
Run Code Online (Sandbox Code Playgroud)
@Entity
data class Model(
        val value: String
) : BaseEntity<UUID>(UUID.randomUUID()) { 

    override fun toString(): String {
        return "Model(value=$value, ${super.toString()})"
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅我的工作示例

注意@field注释-没有注释CreationTimestamp/ UpdateTimestamp 无效