To initialize or not initialize JPA relationship mappings?

后端 未结 4 1259
死守一世寂寞
死守一世寂寞 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:04

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

    import com.google.common.collect.ImmutableList;
    // ...
    @OneToMany(mappedBy="order")
    List 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.

提交回复
热议问题