How do you provide an .orElse() value for fetchOptional()?

7 views
Skip to first unread message

Daniel Einspanjer

unread,
May 8, 2017, 10:36:16 AM5/8/17
to jOOQ User Group
If you have a query that returns Record1<Integer> and you execute the query using fetchOptional(), how can you provide an alternative value in the .orElse() method of the optional?

i.e.

Integer result = select(FOO.MY_INT).from(FOO).where(FOO.BAR.eq("baz")).fetchOptional().orElse(new Record1<Integer>() { -1 });

Lukas Eder

unread,
May 9, 2017, 8:29:14 AM5/9/17
to jooq...@googlegroups.com
The record construction API is available through DSLContext.newRecord():

E.g.

orElseGet(() -> ctx.newRecord(FOO.MY_INT).values(1)));

Of course, you could also solve this with SQL :) E.g.

Integer result = ctx
    .select(FOO.MY_INT)
    .from(FOO)
    .where(FOO.BAR.eq("baz"))
    .unionAll(select(inline(-1)))
    .orderBy(inline(1).desc())
    .limit(1)
    .fetchOne(FOO.MY_INT);

In this case, I think the Java solution is better, though. In fact, I think you were actually looking for this solution:

Integer result = ctx
    .select(FOO.MY_INT)
    .from(FOO)
    .where(FOO.BAR.eq("baz"))
    .fetchOptional()
    .map(Record1::value1)
    .orElse(-1);

Hope this helps,
Lukas

--
You received this message because you are subscribed to the Google Groups "jOOQ User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jooq-user+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Daniel Einspanjer

unread,
May 9, 2017, 8:38:09 AM5/9/17
to jooq...@googlegroups.com
Ahh.. yes that last one is *exactly* what I was looking for. :)

To unsubscribe from this group and stop receiving emails from it, send an email to jooq-user+...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to a topic in the Google Groups "jOOQ User Group" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/jooq-user/H9UYs_nViAw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to jooq-user+...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages