跳至主要內容

Kotlin/Springboot/Mongodb – @DBRef bidirectional relationship causes infinite recursion exception

From my previous post here (https://www.takurohuang.com/2023/06/02/kotlin-springboot-mongodb-dbreflazytrue-cannot-subclass-final-class-error/), I faced those issues while using @DBRef for bidirectional relationship. The infinite recursion issue can happen even when lazy = true if you return the mongodb entity directly without converting it to DTO which needs to take out relationship before returning it back to client.

Beside converting it to DTO, there are also some other ways to get this issue fixed. Introduce to @JsonManagedReference, @JsonBackReference annotation from Jackson.

You can just simply apply it to the variables that you use for bidirectional relationship to tell that the variable is for reference, so do not populate it.

@Document("User")
data class User(
    @Id
    val id: String? = null,
    var name: String,

    @DBRef(lazy=true)
    @JsonManagedReference
    var items: List<Item>? = null
)
@Document("Item")
data class Item(
    @Id
    val id: String? = null,
    var name: String,

    @DBRef(lazy=true)
    @JsonBackReference
    val user: User
)

For more information, you can refer to this post. (https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)

分類:Issues

搶先發佈留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

由 Compete Themes 設計的 Author 佈景主題