Search code examples
springpostgresqlspring-bootjpajooq

Fetching One to Many associations with JooQ


I'm trying to deserialise a one to many association with JooQ (without code generation) as per this post.

Here are my target classes.

public class Author {
    private Long id;
    private String name;
    private List<Book> books;
}

public class Book {
   private String name;
}

My JooQ query is as follows:

dslContext
            .select(table("authors").asterisk(),
                    field(
                      select(jsonArrayAgg(
                                   jsonObject(
                                       jsonEntry("name", field("books.name")))))
                      .from(table("books"))
                      .join(table("authors"))                        
                      .on(field("books.author_id").eq(field("authors.id")))
                      .where(field("emails.collection_case_id")
                        .eq(field("collection_cases.id")))
                    ).as("books"))
            .from(table("authors"))
            .where(trueCondition())
            .fetchInto(Author.class);

The jsonObject() method does not work as expected for me. The generated SQL statement looks something like this:

select authors.*, (select json_agg(json_build_object(?, books.name)) from books join authors ...

The translated postgres query has not properly replaced the key attribute of json_build_object and this results in SQL exception.

PS: I'm using JooQ 3.14.0 with postgres 11.5


Solution

  • While I can't reproduce this issue on my side with various PostgreSQL server and JDBC driver versions, the simple workaround here is to use DSL.inline(String) to prevent jOOQ's generating a bind variable for the json_build_object() function argument:

    jsonEntry(inline("name"), field("books.name"))