Reputation: 47
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.
Upvotes: 0
Views: 200
Reputation: 1868
What about:
public class EntityA {
private List<EntityB> listOfB = new ArrayList<EntityB>();
JPA Tools now generates Entities from tables in this manner and this works fine with JPA.
This is a very nice solution, if you just want to make sure, that the List is initialized (and thus not null). JPA tools seems to take this a bit further and initializes all references to other Entities. EG:
@Entity
public class Entity implements java.io.Serializable {
private OtherEntity otherEntity = new OtherEntity ();
private Set<EntityTwo> entityTwos= new HashSet<EntityTwo>(0);
I would agree, that initializing Lists or Sets (OneToMany) makes sense, since the List can be empty. Initializing an Object of another entity is a bit strange (OneToOne, ManyToOne), since the reference could be non existing. But that is what JPA tool generates.
A Getter is definitely the wrong place for this. In your example the getter changes the state of the object, which is something you wouldn't expect from a getter.
Initializing field in @PostConstruct is a viable solution. But I would prefer it for initializing fields with a specific value or with some more logic.
Upvotes: 1