bleggleb
bleggleb

Reputation: 495

How i can reused/compose part of a JOOQ query in a repository method?

With a JOOQ DSLContext variable ctx I have a method to select all relationship data.

 open fun selectAllSomethings(id: String): List<SomeDto> = ctx
    .select(..), 
    .from(..)
    .join(..)
    .leftJoin(...)
    .fetch()
    .map()

And I need to reused this logic with an add method where for a concrete id I want to change the code to use fetchOne and map. How can I reuse the first part of query and share it between both methods? This part:

ctx.select(..), 
    .from(..)
    .join(..)
    .leftJoin(...)

Is it necessary to divide this into two different methods? Or need to add an if ?

Upvotes: 2

Views: 813

Answers (1)

Jayson Minard
Jayson Minard

Reputation: 85946

This answer is not syntactically perfect -- without having your generated model, nor knowing the full types I can only show a rough sample. The solution would basically be a shared method used by two other methods:

private fun DSLContext.baseThingQuery(id: String): ResultQuery<Record> {
    return select(...)
            .from(...)
            .join(...).on(...)
            .leftJoin(...).on(...)
} 

fun fetchAllThings(id: String): List<ThingDto> {
     return ctx.baseThingQuery(id).fetch(...).map(...)
}

fun doSomethignWithOneThing(id: String): ThingDto {
     return ctx.baseThingQuery(id).fetchOne(...).map(...)
}

Note: I made the shared utility function extend the DSLContext just so that it is more obvious that it is intended as a function to only be used within a context (i.e. transaction) and also private to make it truly internal. You could easily change this to pass in the context as a parameter.

Upvotes: 4

Related Questions