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)
搶先發佈留言