Nested objects jdbi 3 with bean mapper is null

Viewed 30

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?
1 Answers

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 your get method will then be JoinRow, 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 field parent of Child and just the following annotations on the repository method:

@SqlQuery("""
    SELECT 
        c.id as id, c.created as 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)
Related