gpt4 book ai didi

jpa - Micronaut数据:创建并保存新实体

转载 作者:行者123 更新时间:2023-12-02 13:12:45 24 4
gpt4 key购买 nike

我想在应用程序启动期间保留新实体,如下所示:

class Application(
private val bookRepository: BookRepository,
) {
@EventListener
fun init(event: StartupEvent) {
val encyclopedia = BookEntity(0, "The sublime source of knowledge")
val notebook = BookEntity(0, "Release your creativity!")
bookRepository.saveAll(listOf(encyclopedia, notebook))
}
}

根据 the documentation,这应该可以工作,但是由于某种原因,我收到了 javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist异常。

最佳答案

您将ID 0传递给BookEntity构造函数以指示它是一个新实体。它与JDBC一起使用,但是当您使用JPA时,必须将0替换为null。预期的工作如下:

class Application(
private val bookRepository: BookRepository,
) {
@EventListener
fun init(event: StartupEvent) {
val encyclopedia = BookEntity(null, "The sublime source of knowledge")
val notebook = BookEntity(null, "Release your creativity!")
bookRepository.saveAll(listOf(encyclopedia, notebook))
}
}

关于jpa - Micronaut数据:创建并保存新实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57445283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com