Is it mandatory to instantiate collection fields in JPA?

I read an article in which the author implemented the Entity class as follows:

@Entity
public class Product {

 @OneToMany
 private List<Part> parts; // note the missing "= new ArrayList<Part>();"

 public Product() {
 }

 // getters and setters

}

I always used to create instances of collection fields, in this case parts, either inline ( private List<Part> parts = new ArrayList<Part>();), or inside the constructor, since, as far as I remember, this did not lead to the appearance of all kinds of NPE.

I thought that everything changed in JPA 2 and now JPA runtime automatically creates a field using enhancement or reflection of bytecode at runtime, so I gave it another try, however I still can not get it to work without instantiating partsotherwise it aProduct.getParts().add(aPart)will cause NPE.

, , parts Java SE Java EE Hibernate ? , ?

+3
2

, JPA , . , ( ) , , . , Hibernate/JPA , . , ( ): JPA/Hibernate , , - .

, , . , , : Hibernate/JPA "". , factory .

+8

Entity , " " , ( ). null persist(), , , ( , )

+2

Source: https://habr.com/ru/post/1767833/


All Articles