I come from Grails background and have recently started a project in Micronaut using GORM.
I have the following code:
package micronaut.query.association.domain
import org.grails.datastore.gorm.GormEntity
@grails.gorm.annotation.Entity
class Author implements GormEntity<Author> {
String name
static hasMany = [
books: Book
]
static mapping = {
books fetch: 'join'
}
}
package micronaut.query.association.domain
import org.grails.datastore.gorm.GormEntity
@grails.gorm.annotation.Entity
class Book implements GormEntity<Book> {
String name
Author author
}
package micronaut.query.association
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.HttpStatus
import micronaut.query.association.domain.Author
import grails.gorm.transactions.ReadOnly
@groovy.transform.CompileStatic
@Controller("/author")
class AuthorController {
@Get("/")
@ReadOnly
List<Author> index() {
return Author.list()
}
}
The app compiles and starts without problems, but when I try to access the url http:localhost:8080/author, I receive the following error:
10:25:29.431 [nioEventLoopGroup-1-2] ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: Error encoding object [[micronaut.query.association.domain.Author : 1, micronaut.query.association.domain.Author : 2]] to JSON: Infinite recursion (StackOverflowError) (through reference chain: micronaut.query.association.domain.Book["author"]-
| Micronaut Version: 1.0.1 | JVM Version: 1.8.0_192 OS: Linux 4.19.4-arch1-1-ARCH
Am I doing something wrong? Thanks and please forgive me if my message was not posted in the correct way. This is my first try in stack overflow.
Thanks to the excellent article suggested, I was able to solve the problem.
The solution was decorate the books declaration in the Author class with the @JsonManagedReference annotation and decorate the author declaration in the Book class withe the @JsonBackReference annotation.