Video in progress

When should you not map a @OneToMany collection on the entity at all?

When the collection can grow without bound (orders, logs, payments), when it is not part of the aggregate, or when it is only read page by page. In those cases the association exists only on the child side as @ManyToOne, and the list is fetched through a repository query.

📖 Answer

Imagine Customer.orders. A new customer has 3 orders; five years later a loyal customer has 40 thousand. If someone writes customer.getOrders().add(newOrder), Hibernate initializes the bag: 40 thousand rows into memory. The reason is simple: in many cases you have to load the collection to add an element to it (a set, an indexed list, orphanRemoval).

My questions:

  • Is the collection size bounded? Order lines: yes, usually a few dozen. A customer's orders: no.
  • Does the parent use it for its own invariant? An order computes its total from its lines: yes. A customer doesn't need all of its orders.
  • How is the collection read? Paged, filtered, sorted: then it is a query, not a collection.

This is what not mapping it looks like:

@Entity
class Order {
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private Customer customer;
}

interface OrderRepository extends JpaRepository<Order, Long> {
    Page<Order> findByCustomerIdOrderByCreatedAtDesc(long customerId, Pageable p);
}

You lose cascade and orphanRemoval, but you didn't need them here anyway. Deleting a customer is written out explicitly as a business process.

One tip: refactoring away an existing mapping is safe if you start from the mappedBy side, because the owner is on the child side and the schema doesn't change.