简体   繁体   中英

Kotlin JOOQ fetch data and then map static data afterwards

It is possible to map static properties after selecting data from DB? For example if I want that result of some field will be always ENUM_VALUE . I will add an example to make myself more clear.

Target dto I want to fill via JOOQ

internal data class MytargetClass(val property: Int, val static_value: MyEnum)

Since static_value is val and its not optional, I need to initialize that property while creating object. So way to create object only with property and map static_value afterwards is not possible.

This is a solution that works, I add my enum value as string via val method, but this approach is not really something that I would want.

// Repository file, other fields and method omitted for simplicity        
        jooq
        .select(
            t.property.`as`("property"),
            DSL.`val`(Enum.MY_VALUE.name).`as`("static_value"),
        )
        // from and where clause omitted for simplicity
        .fetchInto(MytargetClass::class.java)

But I would like to ask if there is way how to do something like

// Repository file, other fields and method omitted for simplicity   
    jooq
    .select(
        t.property.`as`("property"),
    )
    // from and where clause omitted for simplicity
    .fetchInto(MytargetClass::class.java, (data) -> { data.static_value = Enum.MY_VALUE // possible more transformation of object inside this lambda })

So I dont have to select these properties statically via SQL and therefore I can bypass problems with ENUM dialects and other issues linked to this approach.

Using DefaultRecordMapper

Just use a custom RecordMapper via ResultQuery.fetch(RecordMapper) and call apply on a mapped value

.fetch {
    it.into(MytargetClass::class.java).apply { 
        static_value = Enum.MY_VALUE
    }
}

Using any other RecordMapper

The above just assumes you want to continue using the DefaultRecordMapper , which is reflection based. But you don't have to. You can do anything you want with it :

.fetch {
    MytargetClass(it[t.property], Enum.MY_VALUE)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM