I was reading an article in which the author had implemented an Entity class like this:
@Entity
public class Product {
@OneToMany
private List<Part> parts; // note the missing "= new ArrayList<Part>();"
public Product() {
}
// getters and setters
}
I always used to instantiate collection fields, in this case parts
, either inline (private List<Part> parts = new ArrayList<Part>();
) or inside the constructor because as far as I can remember not doing so would lead to all kinds of NPEs.
I thought that things have changed in JPA 2 and now the JPA runtime automatically instantiates the field using runtime bytecode enhancement or reflection, so I gave it another try, however I still can't get it to work without instantiating the parts
field, otherwise aProduct.getParts().add(aPart)
would throw an NPE.
So my question is that is it possible to make this work without instantiating the parts
field in both of Java SE and Java EE environments using Hibernate as the provider? If so, how?