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

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))
    }
}

10-06 05:47