简体   繁体   中英

Custom POJO with Left Join in jooQ

I'm doing a left join of Table A and Table B and trying to fetch the results into a custom POJO which has fields from both Table A and Table B as follows:

List<MyCustomPojo> res = create.select()
                         .from(TABLE_A)
                         .leftJoin(TABLE_B)
                         .on(TABLE_A.MY_CODE.eq(TABLE_B.MY_CODE))
                         .fetchInto(MyCustomPojo.class);

It works fine for all the fields except for the field myCode the one on which these two tables are joined. For me the values for myCode were picked up from the right table, Table B, which is NULL for all of those records in Table A that do not have a corresponding entry in Table B. I would like to know how jooQ decides which field to map to POJO and if this behavior is documented anywhere.

My goal is to fetch all the fields from Table A and Table B into the custom POJO such that myCode is picked up from the left table. I would appreciate your advice on the right way to achieve it.

The default behaviour of ResultQuery.fetchInto(Class) (and most other into(Class) methods) is specified in DefaultRecordMapper . It can be overridden globally by providing a custom RecordMapperProvider in your Configuration .

In your particular case, DefaultRecordMapper will map all values from your records in field order. If there's a column that appears twice, it will be mapped twice, meaning that the second value will persist in your resulting object. There are two easy workarounds:

Don't select the "wrong" myCode . This is really the most robust solution

List<MyCustomPojo> res = create
    .select(TABLE_A.fields())
    .select(/* all fields in TABLE_B except the ones you don't want */)
    .from(TABLE_A)
    .leftJoin(TABLE_B)
    .on(TABLE_A.MY_CODE.eq(TABLE_B.MY_CODE))
    .fetchInto(MyCustomPojo.class);

Use RIGHT JOIN instead:

Perhaps a bit of a hack, but this will quickly reverse the table order in your SELECT statement.

List<MyCustomPojo> res = create
    .select()
    .from(TABLE_B)
    .rightJoin(TABLE_A)
    .on(TABLE_A.MY_CODE.eq(TABLE_B.MY_CODE))
    .fetchInto(MyCustomPojo.class);

Finally a use-case for RIGHT JOIN :)

Note, this is the only solution that will also prevent wrong values for other columns that "accidentally" share the same name.

Add the "correct" myCode field once more.

Another hack, but it will work around the issue you're experiencing:

List<MyCustomPojo> res = create
    .select(TABLE_A.fields())
    .select(TABLE_B.fields())
    .select(TABLE_A.MY_CODE)
    .from(TABLE_A)
    .leftJoin(TABLE_B)
    .on(TABLE_A.MY_CODE.eq(TABLE_B.MY_CODE))
    .fetchInto(MyCustomPojo.class);

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