分离的实体传递给坚持Kotlin

问题描述 投票:0回答:1

当我尝试持久化实体时,会发生以下错误

org.hibernate.PersistentObjectException:传递给persist的分离实体:xxxxxxx.xxxxxxxx.Invoice

我的模特

@Entity
@Table(name = "invoices")
class Invoice(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long = -1,
        var date: Date,
        @Column(name = "user_id", unique = true)
        var userId: Long,
        @Column(name = "invoice_number")
        var invoiceNumber: String) : Serializable {

    constructor(date: Date, userId: Long, invoiceNumber: String) : this(-1, date, userId, invoiceNumber)
}

发票对象的创建如下

val invoice = Invoice(Date(), 11111, "abc123")

invoiceDao.create(invoice)

在我的通用dao我坚持

fun create(entity: T): T {
    entityManager.persist(entity)

    return entity
}

allopen和noarg包含在我的build.gradle中

hibernate jpa kotlin
1个回答
1
投票

您已将id字段定义为自动生成但为其指定了默认值。当hibernate尝试持久化它时,它认为该对象表示数据库中的基础行,因为它已经有一个id。因此,它认为它是一个独立的对象。 persist()方法不适用于分离的对象。您可以将id的默认值设置为null以解决此问题。

© www.soinside.com 2019 - 2024. All rights reserved.