Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Hibernate 已分离的实体传递给persist Kotlin_Hibernate_Jpa_Kotlin - Fatal编程技术网

Hibernate 已分离的实体传递给persist Kotlin

Hibernate 已分离的实体传递给persist Kotlin,hibernate,jpa,kotlin,Hibernate,Jpa,Kotlin,当我试图持久化一个实体时,会发生以下错误 org.hibernate.PersistentObjectException:传递给的分离实体 保存:xxxxxxxx.xxxxxxxx.Invoice 我的模型 @Entity @Table(name = "invoices") class Invoice( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long = -1

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

org.hibernate.PersistentObjectException:传递给的分离实体 保存:xxxxxxxx.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)
在我的普通道中,我坚持

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

    return entity
}

allopen和noarg包含在我的构建中。gradle

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

您的id属性有默认值吗?这可能就是问题所在。您已将id字段定义为自动生成,但为其指定了默认值。当hibernate试图持久化它时,它认为该对象代表数据库中的一个底层行,因为它已经有了一个id。因此,它认为它是一个分离的对象。我如何在Kotlin中做到这一点?将null设置为id?我还没有完成Kotlin。我想只要您不分配任何内容,它就会被视为null。@Sashi setting var id:long?=null现在可以工作了。请发表一个答案,这样我就可以接受你的:D