pez
pez

Reputation: 1149

jOOQ Return a POJO, and ID from from joined table

I've got a table WARNINGS_HISTORY which is a list of events, each event links to a WARNINGS row which contains details for the event. I've been able to retrieve a list of WARNINGS (List<Warnings>) which occurred in a specific time frame. But I also need to have the WARNINGS_HISTORY.ID. So I need the below SQL to return something like Map<Integer, Warnings>, List<List<Integer, Warnings>> or List<List<WarningsHistory, Warnings>> where the Integer field is theWARNINGS_HISTORY.ID.

Any hints as to how to make this happen?

public List<Warnings> load(int maxId, LocalDateTime timestampStart,LocalDateTime timestampEnd) {
    return create.select(WARNINGS.fields())
            .from(WARNINGS_HISTORY)
            .innerJoin(WARNINGS).using(WARNINGS.SIDFILENAME)
            .where(WARNINGS_HISTORY.IID.greaterThan(maxId))
            .and(WARNINGS_HISTORY.DTCREATEDATE.greaterOrEqual(timestampStart))
            .and(WARNINGS_HISTORY.DTCREATEDATE.lessOrEqual(timestampEnd))
            .orderBy(WARNINGS_HISTORY.IID.asc())
            .fetch().into(Warnings.class);
}   

Upvotes: 3

Views: 269

Answers (1)

Lukas Eder
Lukas Eder

Reputation: 220762

Write this:

public Map<Integer, Warnings> load(
        int maxId, 
        LocalDateTime timestampStart,
        LocalDateTime timestampEnd) {
    return create
            .select(WARNINGS.fields())
            .select(WARNINGS_HISTORY.ID) // Add the ID to the SELECT list
            .from(WARNINGS_HISTORY)
            .innerJoin(WARNINGS).using(WARNINGS.SIDFILENAME)
            .where(WARNINGS_HISTORY.IID.greaterThan(maxId))
            .and(WARNINGS_HISTORY.DTCREATEDATE.greaterOrEqual(timestampStart))
            .and(WARNINGS_HISTORY.DTCREATEDATE.lessOrEqual(timestampEnd))
            .orderBy(WARNINGS_HISTORY.IID.asc())
            .fetchMap(

                // Mapping the Map key is straight forward
                r -> r.get(WARNINGS_HISTORY.ID),

                // Mapping the Map value needs an extra step to avoid the ambiguity
                // between WARNINGS.ID and WARNINGS_HISTORY.ID when you use into(Class),
                // i.e. when you use jOOQ's DefaultRecordMapper
                r -> r.into(WARNINGS).into(Warnings.class)
            );
}   

The above makes use of ResultQuery.fetchMap(RecordMapper, RecordMapper)

Upvotes: 2

Related Questions