Chapter 30: Relationships and JOINs in Java

Connect tables with INNER and LEFT JOIN. In this chapter, you will learn relationships and joins in depth with Java code examples, explanations, and best practices.

Overview

This chapter covers relationships and joins for Kungfu.js developers using Java. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding relationships and joins is essential because it is a core part of building web applications. Every real-world app needs to handle connect tables with inner and left join. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

This chapter covers relationships and joins in Java. Below is a practical code example you can copy, run, and modify to solidify your understanding.

// Define two related models
const { Model } = require('@kungfu/orm');

class User extends Model {
    static table = 'users';
    static fields = {
        id: { primary: true, autoIncrement: true },
        name: String,
        email: { type: String, unique: true },
    };
}

class Post extends Model {
    static table = 'posts';
    static fields = {
        id: { primary: true, autoIncrement: true },
        userId: { type: Number, indexed: true },  // foreign key
        title: String,
        body: String,
    };
}

// INNER JOIN: get all posts by user 42
const posts = await Post.select()
    .innerJoin('users', 'posts.user_id = users.id')
    .where('users.id = 42')
    .orderBy('posts.id', 'DESC')
    .all();

// LEFT JOIN: get all users and their posts
const rows = await db.queryRaw(
    'SELECT users.name, posts.title FROM users LEFT JOIN posts ON posts.user_id = users.id'
);

Why This Matters

Every feature in Kungfu.js is designed to be predictable: the same input always produces the same output, the same route always hits the same handler, and the same middleware always runs in the same order. This predictability is what makes production apps maintainable. When something breaks at 3 AM, you need to reason about the request path quickly — and the onion-model middleware plus the trie router give you that mental model for free.

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about relationships and joins in Java. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 31, we will cover Password Hashing: Argon2id hashing and verification.