16

What support is there for querying into postgres json objects with JOOQ?

For example,

SELECT id, data->'author'->>'first_name' as author_first_name FROM books;
Joel
  • 2,601
  • 4
  • 33
  • 44

1 Answers1

30

Many standard SQL/JSON operators like JSON_ARRAY(), JSON_OBJECT(), JSON_ARRAYAGG() and a few more are supported starting from jOOQ 3.14.

Currently (as of jOOQ 3.15), support for these vendor specific JSON operators is still not implemented: https://github.com/jOOQ/jOOQ/issues/10018

However, you can always resort to using plain SQL. Your query can be expressed as such with jOOQ:

DSL.using(configuration)
   .select(BOOKS.ID, field("{0}->'author'->>'first_name'", 
                       String.class, BOOKS.DATA
                     ).as("author_first_name"))
   .from(BOOKS)
   .fetch();

For details, see the DSL.field() methods javadocs.

Or, write your own mini API

If you're using a lot of these JSON path notations, you might be able to factor out a mini API as such:

public static Field<Object> jsonObject(Field<?> field, String name) {
    return DSL.field("{0}->{1}", Object.class, field, DSL.inline(name));
}

public static Field<String> jsonText(Field<?> field, String name) {
    return DSL.field("{0}->>{1}", String.class, field, DSL.inline(name));
}

The above could then be used as such:

DSL.using(configuration)
   .select(BOOKS.ID, jsonText(jsonObject(BOOKS.DATA, "author"), "first_name")
                     .as("author_first_name"))
   .from(BOOKS)
   .fetch();
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
  • Just a comment on this. I understand how to use Plain SQL to manually handle the Postgres JSON data type, but it would be nice if there were a way to get the `UpdatableRecord` to support json, even if in a slightly hackish way. We use `create.newRecord( MY_TABLE, MyPojo )` all the time and I haven't found an elegant way to handle INSERT or UPDATE for json columns. – Josh Padnick Sep 03 '14 at 23:00
  • @JoshPadnick: What kind of `INSERT` or `UPDATE` would you want to be doing? Just plain data, or some JSON function calls? Best ask a new question, though. It'll be easier to answer than with comments... – Lukas Eder Sep 04 '14 at 05:52
  • is this answer still a viable solution now? – Brunaldo Jul 06 '21 at 11:06
  • 1
    @Brunaldo: Thanks for the ping. Slightly outdated, but in this particular case, yes, the `->` operator and the likes are not yet supported. See the workarounds offered in my answer. – Lukas Eder Jul 06 '21 at 11:10