To initialize or not initialize JPA relationship mappings?

后端 未结 4 1240
死守一世寂寞
死守一世寂寞 2021-01-01 12:58

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

@Entity
public class Order {          


        
4条回答
  •  北海茫月
    2021-01-01 13:11

    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.

提交回复
热议问题