Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting conditions with jooq

Tags:

java

sql

jooq

In SQL, I can execute a query of type:

SELECT cost > 1000 AS above_k, name FROM products;

Giving me a list:

+---------+--------+
| above_k | name   |
+---------+--------+
| true    | Gold   |
| false   | Silver |
+---------+--------+

How can I model a similar query using jooq? I cannot do this (obviously):

ctx.select(Tables.PRODUCTS.COST.gt(1000))

Since, there is no method select(Condition condition). Or if I just wanted to:

SELECT cost*0.9 AS discounted_cost FROM products;

Is there a way to do this using jooq?

like image 907
Rohan Prabhu Avatar asked Jan 08 '23 11:01

Rohan Prabhu


1 Answers

SQL 1:

SELECT cost > 1000 AS above_k, name 
FROM products;

jOOQ 1:

ctx.select(field(PRODUCTS.COST.gt(1000)).as("above_k"), PRODUCTS.NAME)
   .from(PRODUCTS)
   .fetch();

See DSL.field(Condition)

SQL 2:

SELECT cost*0.9 AS discounted_cost 
FROM products;

jOOQ 2:

ctx.select(PRODUCTS.COST.mul(0.9).as("discounted_cost"))
   .from(PRODUCTS)
   .fetch();

See Field.mul(Number) or Field.multiply(Number)

like image 110
Lukas Eder Avatar answered Jan 14 '23 22:01

Lukas Eder