I have a child class with a member variable nested as defined below. However, when I run
val child = childRepo[1]
child.parent is null. How can I automatically fetch the nested member variable?
Models.kt
import org.jdbi.v3.core.mapper.Nested
data class Child(
var id: Int = -1,
@Nested
var parent: Parent? = null,
var created: Instant? = null
)
data class Parent(
var id: Int = -1,
)
ChildRepo.kt
import org.jdbi.v3.sqlobject.config.RegisterBeanMapper
import org.jdbi.v3.sqlobject.statement.SqlQuery
@SqlQuery("""
SELECT
c.id as c_id, c.created as c_created,
p.id as p_id
FROM child as c
INNER JOIN parent p on p.id = c.parent_id
WHERE c.id = :id
""")
@RegisterBeanMapper(value = Child::class, prefix = "c")
@RegisterBeanMapper(value = Parent::class, prefix = "p")
operator fun get(id: Int): Child?
You'll get the closest thing to your repository snippet if you also register a
JoinRowMapper(e.g. with@RegisterJoinRowMapper) for the two classes. The return type of yourgetmethod will then beJoinRow, from which you can retrieve the two values.There's more info and some examples here: https://jdbi.org/#_joins
If you're comfortable setting the prefix in the class definition, something that might be easier is putting
@Nested("p")on the fieldparentofChildand just the following annotations on the repository method: