Video in progress

Strong Middle 🐻 Hibernate and JPA

Why does a unidirectional `@OneToMany` (without `mappedBy`) send more SQL than you'd expect?

Without @JoinColumn, Hibernate creates a separate join table. With @JoinColumn, it first INSERTs the child without the FK, then sets the FK with a separate UPDATE. As a result there are two statements per child, and making the FK column NOT NULL gets harder.

📖 Answer

Variant A: without @JoinColumn:

@Entity
class Invoice {
    @OneToMany(cascade = CascadeType.ALL)
    private List<InvoiceLine> lines = new ArrayList<>();
}

Hibernate expects a join table named invoice_lines: three tables instead of two, an extra JOIN on every read, and when you remove from a bag, the join table gets rewritten entirely.

Variant B: with @JoinColumn(name = "invoice_id"). The schema is right, but the SQL is:

insert into invoice_line (id, amount) values (?, ?)        -- no invoice_id
update invoice_line set invoice_id = ? where id = ?

The reason: the child side knows nothing about the association. The "collection owner" controls the FK, and it writes it during the stage where the collection is processed. If invoice_id is NOT NULL, the first INSERT fails. Putting @JoinColumn(nullable = false) tells Hibernate to include the FK in the INSERT, but that doesn't cover every case either.

The cleanest way is a bidirectional association with the child as the owner:

@OneToMany(mappedBy = "invoice", cascade = CascadeType.ALL, orphanRemoval = true)
private List<InvoiceLine> lines = new ArrayList<>();

// in InvoiceLine:
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Invoice invoice;

Now there's a single INSERT and the FK is written in one go.

Or the other way round: keep only the @ManyToOne and drop the collection from the entity entirely: when you need it, lineRepo.findByInvoiceId(id). If the collection could get large (thousands of rows), that's exactly what I choose.