I have two entities: Book and Page. Book can have many pages.
@Entity(name = "book")
@RegisterForReflection
internal data class Book (
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
val bookId: Long? = null,
@OneToMany(mappedBy = "book", fetch = FetchType.LAZY)
@Fetch(FetchMode.JOIN)
val pages: MutableSet<Page> = mutableSetOf(),
)
@Entity(name = "page")
@RegisterForReflection
internal data class Page(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
val pageId: Long? = null,
@ManyToOne(fetch = FetchType.LAZY)
@Fetch(FetchMode.JOIN)
@JsonIgnore
var book: Book? = Book(),
)
Both entities are persisted and created in database fine. But if I try to fetch Book, I get LazyInitializationException
. Although I've tried fetching it with Mutiny.fetch or using LEFT JOIN FETCH it always throws the same error. Below the way I persist/fetch:
@ApplicationScoped
internal class BookRepo : PanacheRepository<Book> {
fun getBook(bookId: Long): Uni<Book> {
return findById(bookId)
.call { it -> Mutiny.fetch(it.pages) }
.map {
it ?: throw RuntimeException("Not Found")
}
}
fun persistBook(book: Book): Uni<Book> {
return Panache.withTransaction {
persist(book)
}
}
}
@ApplicationScoped
internal class PageRepo : PanacheRepository<Page> {
fun persistPage(page: Page, bookId: Long): Uni<Page> {
return Panache.withTransaction {
getSession().chain { s ->
val book = s.getReference(Book::class.java, bookId)
page.book = book
persist(page)
}
}
}
}
What am I doing wrong? I've created a repo with this small example, there are sequence of CURL requests to reproduce the error (please check the readme file).