To initialize or not initialize JPA relationship mappings?

JPA itself doesn't care whether the collection is initialized or not. When retrieving an Order from the database with JPA, JPA will always return an Order with a non-null list of OrderLines.

Why: because an Order can have 0, 1 or N lines, and that is best modeled with an empty, one-sized or N-sized collection. If the collection was null, you would have to check for that everywhere in the code. For example, this simple loop would cause a NullPointerException if the list was null:

for (OrderLine line : order.getLines()) {
    ...
}

So it's best to make that an invariant by always having a non-null collection, even for newly created instances of the entity. That makes the production code creating new orders safer and cleaner. That also makes your unit tests, using Order instances not coming from the database, safer and cleaner.


I would rather prefer an utility like this:

public static <T> void forEach(Collection<T> values, Consumer<T> consumer) {
  if (values != null) values.stream().forEach(consumer);
}

and use it in code like:

Utils.forEach(entity.getItems(), item -> {
    // deal with item
});

I would also recommend using Guava's immutable collections, e.g.,

import com.google.common.collect.ImmutableList;
// ...
@OneToMany(mappedBy="order")
List<LineItem> lineItems = ImmutableList.of();

This idiom never creates a new empty list, but reuses a single instance representing an empty list (the type does not matter). This is a very common practice of functional programming languages (Scala does this too) and reduces to zero the overhead of having empty objects instead of null values, making any efficiency argument against the idiom moot.