Available in versions: Dev (3.20) | Latest (3.19) | 3.18 | 3.17 | 3.16 | 3.15

@OneToMany or @ManyToMany

Applies to ✅ Open Source Edition   ✅ Express Edition   ✅ Professional Edition   ✅ Enterprise Edition

In JPA, you may have a @OneToMany mapping like this:

@Entity
public class Author {

    @OneToMany(mappedBy = "author")
    private Set<Book> items;

    // [...]
}

In JPA, you get to specify whether such associations should be fetched eagerly or lazily. In jOOQ, this is irrelevant as you will always express your intent explicitly via a query. Nothing is ever done automatically.

From a mapping perspective, it can be convenient to nest a set (or list, whatever) of child objects in the parent object (irrespective of whether this is a @OneToMany or @ManyToMany relationship). In jOOQ, such a mapping is always ad-hoc, on a per query basis, so it does not need to reflect your actual database model. For example, you can easily "nest" a set of Language values in a BookStore, as we'll see later. With jOOQ, nesting is done directly in SQL using ORDBMS features (native or emulated).

So, instead of having entity classes, you might have DTOs like these (note, we might not need to project the ID):

public record Book(String title) {}
public record Author(String firstName, String lastName, List<Book> books) {}

The DTOs may be reusable or ad-hoc, per query, it's entirely up to you. And you map your query data into the above records as follows:

create.select(
           AUTHOR.FIRST_NAME,
           AUTHOR.LAST_NAME,

           // Nested collection here:
           multiset(
               select(BOOK.TITLE)
               .from(BOOK)
               .where(BOOK.AUTHOR_ID.eq(AUTHOR.ID))

           // Ad-hoc converter here:
           ).convertFrom(r -> r.map(Records.mapping(Book::new))))
      .from(AUTHOR)

      // Ad-hoc converter here
      .fetch(Records.mapping(Author::new));

The above mapping is completely compile time type safe.

Some of the jOOQ features used in this section are:

Feedback

Do you have any feedback about this page? We'd love to hear it!

The jOOQ Logo