eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Introduction

jOOQ (Java Object Oriented Querying) is a powerful library that simplifies database interaction in Java by enabling us to write SQL queries in an object-oriented manner. Joining tables is a fundamental operation in relational databases, allowing us to combine data from multiple tables based on a specific condition. In this tutorial, we’ll explore various types of joins available in jOOQ.

2. Setting up jOOQ

Joining two tables using jOOQ involves utilizing the DSL (Domain Specific Language) provided by jOOQ to construct SQL queries.

To use jOOQ, we’ll need to add the jOOQ and PostgreSQL dependencies to our Maven project’s pom.xml file:

<dependency>
    <groupId>org.jooq</groupId>
    <artifactId>jooq</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
</dependency>

Before using joins, we need to establish a connection to the database using jOOQ. Let’s create a method getConnection() to obtain the DSLContext object for database interaction:

public static DSLContext getConnection() {
    try {
        Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        DSLContext context = DSL.using(conn, SQLDialect.POSTGRES);
        return context;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

We’ll use the context object throughout the tutorial to interact with the database:

DSLContext context = DBConnection.getConnection();

Additionally, jOOQ provides a code generator that generates Java classes based on our database schema. We’ll assume that the tables Store, Book and BookAuthor are created in the database with their respective schemas.

Next, we can insert test data using the DSLContext object within a method annotated @BeforeClass to ensure it runs before each test. Let’s integrate the test data insertion into our setup method:

@BeforeClass
public static void setUp() throws Exception {
    context = DBConnection.getConnection();
    
    context.insertInto(Tables.STORE, Store.STORE.ID, Store.STORE.NAME)
      .values(1, "ABC Branch I ")
      .values(2, "ABC Branch II")
      .execute();

    context.insertInto(Tables.BOOK, Book.BOOK.ID, Book.BOOK.TITLE, Book.BOOK.DESCRIPTION, 
      Book.BOOK.AUTHOR_ID, Book.BOOK.STORE_ID)
      .values(1, "Article 1", "This is article 1", 1, 1)
      .values(2, "Article 2", "This is article 2", 2, 2)
      .values(3, "Article 3", "This is article 3", 1, 2)
      .values(4, "Article 4", "This is article 4", 5, 1)
      .execute();

    context.insertInto(Tables.BOOKAUTHOR, Bookauthor.BOOKAUTHOR.ID, Bookauthor.BOOKAUTHOR.NAME, 
      Bookauthor.BOOKAUTHOR.COUNTRY)
      .values(1, "John Smith", "Japan")
      .values(2, "William Walce", "Japan")
      .values(3, "Marry Sity", "South Korea")
      .values(4, "Morry Toh", "England")
      .execute();
}

3. Using the join Clause

In jOOQ, SelectJoinStep<Record> is an interface that represents a step within the process of building a SELECT query with joins. We can use methods like select() to specify which columns we want to retrieve from the tables involved.

The join() method in jOOQ is used to perform an inner join between tables based on a specified condition. An inner join retrieves rows where a specific condition is met in both tables.

Here’s an example of joining the Book and BookAuthor tables based on the author ID:

SelectJoinStep<Record> query = context.select()
  .from(Tables.BOOK)
  .join(Tables.BOOKAUTHOR)
  .on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)));

assertEquals(3, query.fetch().size());

Here’s an extended example to demonstrate joining multiple tables:

SelectJoinStep<Record> query = context.select()
  .from(Tables.BOOK)
  .join(Tables.BOOKAUTHOR)
  .on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)))
  .join(Tables.STORE)
  .on(field(Tables.BOOK.STORE_ID).eq(field(Tables.STORE.ID)));

assertEquals(3, query.fetch().size());

We added another join to the Store table. This join operation connects the Book and Store tables based on the STORE_ID column in the Book table and the ID column in the Store table. By adding this additional join, the query now retrieves data from three tables: Book, BookAuthor, and Store.

4. Using Outer Joins

jOOQ supports various join types beyond the default inner join, such as outer joins. Outer joins allow us to retrieve records even if there is no matching record in the joined table.

4.1. Left Outer Join

A left join includes all rows from the left table Book and matching rows from the right table BookAuthor. Any unmatched rows from the right table will have null values for columns specific to authors.

Let’s see how to perform a left outer join using jOOQ:

SelectJoinStep<Record> query = context.select()
  .from(Tables.BOOK)
  .leftOuterJoin(Tables.BOOKAUTHOR)
  .on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)));

assertEquals(4, query.fetch().size());

In the output, the last row’s author column displays null instead of a corresponding author entry:

+----+---------+---------+-----------------+--------+------+-------------+-------+
|  id|author_id|title    |description      |store_id|    id|name         |country|
+----+---------+---------+-----------------+--------+------+-------------+-------+
|   1|        1|   Book 1|This is    book 1|       1|     1|John Smith   |Japan  |
|   2|        2|   Book 2|This is    book 2|       2|     2|William Walce|Japan  |
|   3|        1|   Book 3|This is    book 3|       2|     1|John Smith   |Japan  |
|   4|        5|   Book 4|This is    book 4|       1|{null}|{null}       |{null} |
+----+---------+---------+-----------------+--------+------+-------------+-------+

When performing a left outer join, as demonstrated in the query, all rows from the left table Book are included in the result set. In this case, even though there is no matching author_id in the BookAuthor table for the last row, it still appears in the output. However, since there are no corresponding data available in the BookAuthor table, the columns specific to authors (id, name, country) have null values for this row.

4.2. Right Outer Join

In contrast, a right join encompasses all rows from the right table BookAuthor and matches them with rows from the left table Book. Rows from the left table that don’t match any entries in the right table will have null values for book-specific columns.

Let’s see how to perform a right outer join using jOOQ:

SelectJoinStep<Record> query = context.select()
  .from(Tables.BOOK)
  .rightOuterJoin(Tables.BOOKAUTHOR)
  .on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)));

assertEquals(5, query.fetch().size());

Similarly to the left outer join, in the output, the last two authors don’t have associated book records, resulting in null values:

+------+---------+---------+-----------------+--------+----+-------------+-----------+
|    id|author_id|title    |description      |store_id|  id|name         |    country|
+------+---------+---------+-----------------+--------+----+-------------+-----------+
...
|{null}|   {null}|{null}   |{null}           |  {null}|   4|Morry Toh    |England    |
|{null}|   {null}|{null}   |{null}           |  {null}|   3|Marry Sity   |South Korea|
+------+---------+---------+-----------------+--------+----+-------------+-----------+

4.3. Full Outer Join

A full outer join combines all rows from both tables Book and BookAuthor, regardless of whether there’s a match. Rows that don’t have a match in the opposite table have null values for columns from that table.

To perform a full outer join in jOOQ, we can use the following syntax:

SelectJoinStep<Record> query = context.select()
  .from(Tables.BOOK)
  .fullOuterJoin(Tables.BOOKAUTHOR)
  .on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)));

assertEquals(6, query.fetch().size());

5. Using Natural Joins

Natural joins automatically determine the join condition based on matching column names. This can be helpful when the join condition is straightforward using a common column like AUTHOR_ID:
SelectJoinStep<Record> query = context.select()
  .from(Tables.BOOK)
  .naturalJoin(Tables.BOOKAUTHOR);

assertEquals(4, query.fetch().size());
However, if column names aren’t intended for joining or data types don’t match, unintended results might occur. In the output, we observe that one of the records was matched incorrectly:
+----+---------+---------+-----------------+--------+----+-------------+-------+
|  id|author_id|title    |description      |store_id|  id|name         |country|
+----+---------+---------+-----------------+--------+----+-------------+-------+
...
|   4|        5|   Book 4|This is    book 4|       1|   4|Morry Toh    |England|
+----+---------+---------+-----------------+--------+----+-------------+-------+

6. Using Cross Joins

Cross joins are the most basic type of join, where every row from one table is combined with every row from the other table. This can be useful in specific scenarios where we have a table of Store and Book. We want to display a list of all possible store-book combinations.

Let’s examine the outcome when we execute a cross join:

SelectJoinStep<Record> query = context.select()
  .from(Tables.STORE)
  .crossJoin(Tables.BOOK);

assertEquals(8, query.fetch().size());

A cross join efficiently produces every possible combination, enabling us to showcase options like “Branch I – Book 1“, “Branch I – Book 2“, and so forth. However, cross joins should be used cautiously due to the potential for creating very large datasets, especially if the tables involved have many rows.

7. Conclusion

In this article, we learned how to join tables in jOOQ. We discussed various types of joins, including inner joins, outer joins (left, right, and full outer), natural joins, and cross joins. Moreover, we saw that natural joins and cross joins can be useful but should be used carefully due to potential unintended results or performance issues, especially with large datasets.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments