简体   繁体   中英

jOOQ: reusing / copying queries

In order to avoid re-creating the same part of a dynamic query over and over again, I was going to build the main part once and then reuse this part in different parts of the application. Since building the query is somewhat involved (see question jOOQ: best way to get aliased fields (from #as(alias, aliasFunction)) for one aspect of why this is the case), this should benefit performance...

Unfortunately, I've had to realize that the different "steps" in the builder pattern don't return amended copies, but modify underlying state. Thus, I've looked for a way to create an immutable copy of a specific "step" (eg SelectWhereStep ) from which to initialize and subsequently amend a (Select-)query each time I need it. Unfortunately, I haven't been able to identify any ("legal") way of achieving this.

Can it be done? If not, what's the best alternative?

Unfortunately, I've had to realize that the different "steps" in the builder pattern don't return amended copies, but modify underlying state

This is indeed a very unfortunate limitation in the current design of the jOOQ DSL / model APIs . The DSL API should be immutable whereas the model API is the mutable one. But this isn't always the case as you've noticed.

There is currently no way to clone a jOOQ query as mostly, this is not really necessary. Regardless if you're operating with a mutable or immutable API, the cleanest way to achieve what you want to do is to compose jOOQ queries in a functional way. Ie instead of

I was going to build the main part once and then reuse this part in different parts of the application

You could just do the same thing in a functional way rather than an imperative way. Rather than assigning "the main part" to some local or global variable, you could make a theMainPart() function that returns that part on the fly. More about this in this blog post .

As a side-note, when writing dynamic SQL, there are usually better ways than referencing the XYZStep types directly .

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