How i can reused/compose part of a JOOQ query in a repository method? has a good answer for multiple queries that start the same way with different later components.
What if, instead, I want to reuse some logic that appears in the middle of multiple queries, or at the end? Below is an example where I’m limiting the number of rows joined from a table:
select(TABLE1.FOO, TABLE2.BAR)
.from(TABLE1)
// I want to reuse the code from HERE
.leftJoin(TABLE2)
.on(TABLE2.FOREIGN_ID.eq(TABLE1.ID))
.and(
TABLE2.ID.eq(
ctx.select(TABLE2.ID)
.from(TABLE2)
.where(TABLE2.FOREIGN_ID.eq(TABLE1.ID))
.limit(1)))
// to HERE
.join(TABLE3)
.on(ETC)
That middle block of code is going to look very similar every time I use it. The parts that change are TABLE2
, TABLE2.ID
, and TABLE2.FOREIGN_ID.eq(TABLE1.ID)
. TABLE2.ID
might be implicit if TABLE2
has a unique key. TABLE2.FOREIGN_ID.eq(TABLE1.ID)
might be implicit if FOREIGN_ID
is a foreign key and TABLE1 is within scope to access.
Is there a way to do this that I can chain with existing jooq methods?
select(TABLE1.FOO, TABLE2.BAR)
.from(TABLE1)
.MyUniqueJoinMethod(TABLE2, TABLE2.ID, TABLE2.FOREIGN_ID.eq(TABLE1.ID))
.join(TABLE3)
.on(ETC)
Or will I have to build it as a standalone function that wraps the first half of the query in a more ugly fashion?
MyUniqueJoinFunction(TABLE2, TABLE2.ID, TABLE2.FOREIGN_ID.eq(TABLE1.ID),
select(TABLE1.FOO, TABLE2.BAR)
.from(TABLE1)
).join(TABLE3)
.on(ETC)
To be clear, this particular join-with-limit functionality is not the only place I want to apply an answer to this question. I want to be able to break arbitrary query components out into a function/method, in the same way that the answer to the older linked question allows for leading query components.