Micronaut 数据:创建和保存新实体
Micronaut Data: create and save new entity
我想在应用程序启动期间持久化新实体,如下所示:
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))
}
}
我想在应用程序启动期间持久化新实体,如下所示:
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))
}
}