Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map fetch/result from jooq to specific Record

Tags:

java

casting

jooq

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...
}
like image 459
aksamit Avatar asked Jul 16 '13 20:07

aksamit


2 Answers

@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(?);
like image 187
Syed Shahul Avatar answered Nov 14 '22 23:11

Syed Shahul


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...
}
like image 43
Lukas Eder Avatar answered Nov 14 '22 23:11

Lukas Eder