aksamit
aksamit

Reputation: 2443

Map fetch/result from jooq to specific Record

When I currently query with Jooq I am explicitly casting each record-object to the expected record-type.

Result<Record> result = sql.select().from(Tables.COUNTRY).fetch();
for (Record r : result) {
    CountryRecord countryRecord = (CountryRecord) r;
    //Extract data from countryRecord
    countryRecord.getId();
}

Is it, with Jooq, possibly to cast the result straight into the desired record-type?

Such as (this does not compile):

Result<CountryRecord> countryRecords = (Result<CountryRecord>) sql.select().from(Tables.COUNTRY).fetch();
for (CountryRecord cr : countryRecords) {
    cr.getNamet();
    //etc...
}

Upvotes: 8

Views: 15994

Answers (2)

Syed Shahul
Syed Shahul

Reputation: 481

@Lukas,

Actually we are using fetchInto() to convert the results to list of object.

For example:

Employee pojo matching database table is employee.

List<Employee> employeeList = sql.select(Tables.Employee)
                                 .from(Tables.EMPLOYEE).fetchInto(Employee.class);

similarly, how could we convert the records we are fetching using joins?

For example:

Customer pojo matching database table is customer.

Employee pojo matching database table is employee.

sql.select(<<IWantAllFields>>).from(Tables.CUSTOMER)
                              .join(Tables.EMPLOYEE)
                              .on(Tables.EMPLOYEE.ID.equal(Tables.CUSTOMER.EMPLOYEE_ID))
                              .fetchInto(?);

Upvotes: 9

Lukas Eder
Lukas Eder

Reputation: 220952

You shouldn't be using the select().from(...) syntax when you want to fetch generated record types. Use selectFrom() instead. This is documented here:

http://www.jooq.org/doc/3.1/manual/sql-execution/fetching/record-vs-tablerecord

So your query should be:

Result<CountryRecord> countryRecords = sql.selectFrom(Tables.COUNTRY).fetch();
for (CountryRecord cr : countryRecords) {
    cr.getNamet();
    //etc...
}

Upvotes: 9

Related Questions