Home » Mysql » How to select from only one table in jOOQ using a query with a join?

How to select from only one table in jOOQ using a query with a join?

Posted by: admin January 31, 2018 Leave a comment

Questions:

I have the following query in jOOQ:

factory()
.select()
.from(PERSON)
.join(ENDUSER).on(ENDUSER.PERSON_FK.equal(PERSON.ID))
.where(ENDUSER.ID.equal(userId))
.fetchOne();

This query returns to me a Record with all columns from PERSON and ENDUSER, but I only want the columns from PERSON (that’s why I put .from(PERSON) and not .from(PERSON, ENDUSER)).
I know it doesn’t matter that much but I don’t want unnecessary fields to be returned.

Answers:

You can access the fields in PERSON through the Table.fields() method:

factory()
.select(PERSON.fields()) // Or getFields() in jOOQ 2.x
.from(PERSON)
.join(ENDUSER)...

This is about the same as writing

SELECT PERSON.*
FROM PERSON
JOIN ENDUSER ...

Another option is to actually list all the fields from person one by one

Questions:
Answers:

Lukas’s answer was exactly what I was looking for. You can also use the into() method to get a strongly typed response object back for only the table you care about (instead of the generic Record type):

PersonRecord record = factory()
  .select()
  .from(PERSON)
  .join(ENDUSER).on(ENDUSER.PERSON_FK.equal(PERSON.ID))
  .where(ENDUSER.ID.equal(userId))
  .fetchOne()
  .into(PERSON);