不能使用 Kotlin 配置带有抽象类的 Spring JPA 实体

Yua*_*Cao 4 configuration spring jpa kotlin

我试图在 Spring 项目中使用 Kotlin,我发现实体扩展了抽象类。Kotlin 无法分辨抽象类中的注解。配置如下。

基地.kt

package io.qiyue.dream.entity

import org.hibernate.annotations.GenericGenerator
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.LastModifiedBy
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.LocalDateTime
import javax.persistence.Column
import javax.persistence.EntityListeners
import javax.persistence.GeneratedValue
import javax.persistence.Id

@EntityListeners(AuditingEntityListener::class)
abstract class Base {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "id")
    open var id: String? = null

    @Column(name = "last_modified_at")
    @LastModifiedDate
    open val lastModifiedAt: LocalDateTime? = null

    @Column(name = "last_modified_by")
    @LastModifiedBy
    open val lastModifiedBy: String? = null

    @Column(name = "created_by")
    @CreatedBy
    open val createdBy: String? = null

}
Run Code Online (Sandbox Code Playgroud)

角色.kt

package io.qiyue.dream.entity

import javax.persistence.*

@Entity
@Table(name = "q_role")
open class Role (val name: String) : Base(){
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*lli 5

这在 Java 中也不起作用。

您需要将 @MappedSuperclass 添加到您的基类中,以告诉 JPA 它必须包含基类中的所有属性:

@EntityListeners(AuditingEntityListener::class)
@MappedSuperclass
abstract class Base {
Run Code Online (Sandbox Code Playgroud)