Search code examples
javahibernatejpaeclipselinkopenjpa

To initialize or not initialize JPA relationship mappings?


In one to many JPA associations is it considered a best practice to initialize relationships to empty collections? For example.

@Entity
public class Order { 

   @Id
   private Integer id;

   // should the line items be initialized with an empty array list or not?
   @OneToMany(mappedBy="order")
   List<LineItem> lineItems = new ArrayList<>();

}

In the above example is it better to define lineItems with a default value of an empty ArrayList or not? What are the pros and cons?


Solution

  • 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.