I'm working on a java enterprise application using JPA.I'll explain my doubt showing an example.
My EntityA has a field (that gets persisted in a dabase using a join table) representing a list of EntityB as follows.
public class EntityA {
private List<EntityB> listOfB;
*getter and setter for listOfB*
}
I don't want my getter for listOfB to return null in any case. What is the best point in the code where I can initialize listOfB if it's null?
The first solution I thought about was modifying the getter:
public List<EntityB> getListOfB(){
if(listOfB == null)
listOfB = new ArrayList<EntityB>();
return listOfB;
}
Then I considered using a method marked with @PostConstruct:
@PostConstruct
public void postConstruct() {
if(listOfB == null)
listOfB = new ArrayList<EntityB>();
}
I guess another option would be modifying the constructor.
What is the best approach? More than everything I'm asking this because I don't want any issue to happen due to the interaction with the JPA functionalities. I's also like to know about any issues that the three previously mentioned solutions could originate.